Home > Mobile >  Traversing through list to output different text files
Traversing through list to output different text files

Time:01-08

I am trying to have my code read through one text file in Python, and replace each string of "873" in the text file to whatever is in my array, and to output a text file for each of the elements in the array.

So far I have achieved about 75% of this. My code right now grabs the text file, produces a text file for each element in the array, but only actually writes to text to the first output text file from my array. In the rest of the output text files produced, it is a blank file for each.

Here is what I have:

fin = open("C:\\Users\\...input.txt", "rt")

items = ["sup", "how", "are", "you"]
for item in items:
    with open ("{}outputs.txt".format(item), "w") as f:
        for line in fin:
            f.write(line.replace('873', item))

fin.close()

this does as expected for "sup", replicating the input.txt but replacing each "873" with "sup". (supoutputs.txt) but for the rest of the outputs produced (howoutputs.txt, areoutputs.txt, yououtputs.txt) there is nothing in the file.

CodePudding user response:

Once you iterate through fin once, the cursor for that file is at the end of the file. If you want to iterate through fin a second time, use seek to move the cursor back to the beginning of the file.

CodePudding user response:

You have to use seek(), because this is used to change the position of the File Handle to a given specific position. File handle is like a cursor, which defines from where the data has to be read or written in the file

So the solution to your problem is:

fin.seek(0, 0)
  •  Tags:  
  • Related