0

I am attempting to replace occurrences of '2' with a '1' that appear in a specific column in the text file, for every line in the text file. A line from the text file could look like "2,4,5,3,1". Here's my code for replacing any '1' in column 4:

with open("test.txt","r+") as file1:
    position = 3
    text1 = csv.reader(file1)
    for line in file1:
        index = line.find("1") // 2
        data = list(line)
        if index == position:
            for i in range(5):
                if data[i] == "1":
                    data[i] = 2
                elif data[i] == "2":
                    data[i] = 1
            print(data)
            file1.write(str(data))

When I print data it leaves all the commas and empty space in. It also doesn't replace the correct values in the text file. I really don't have much of an idea to how I would replace specific numbers - my code is probably very bad. Any help will be appreciated.

Ben A
  • 33
  • 5

0 Answers0