Search code examples
pythonfilepython-3.xio

Python: Why do my loops on a certain text file read empty lines although the file is not empty?


I was trying to learn and experiment with Python today, and I got into trying to open a text file, reading the lines from it, and then writing those lines in a 2nd text file. After that, I tried to load the lines from both files into lists, and print those lists in the console. Here is the experimental code:

f = open('D:\\origFile.txt', 'r')
f2 = open('D:\\copyFile.txt', 'w')

for line in f:
    f2.write(line.rstrip() + ' ')
f2.close()

s=""
for linez in f:
    s += linez
    print (s)

s2=""
f2 = open('D:\\copyFile.txt', 'r+')
reading = f2.readlines()
print (reading)

for linex in f2:
    s2 += linex
    print (linex)

list1=s.split()
list2=s2.split()
print(list1)
print(list2)
f.close()
f2.close()

The code works as expected only when I remove or comment this part:

f2 = open('D:\\copyFile.txt', 'w')

for line in f:
    f2.write(line.rstrip() + ' ')
f2.close()

Although I'm already closing f2 file after writing the contents of f1 to it. So why does it affect the rest of the file operations in the code? And how does it still affect f1? As in, the lists in the end are neither populated by the text from f1 nor f2.

Edit 1: In my question, I already tried to close the second file thinking that it would be the cause of my problem, not the loop itself; while the other question didn't even have a loop to satisfy an answer to my question. Although the answers are somewhat the same, the answer in the other question doesn't show how to use the contents of the file repeatedly without having to reset the iterator using f.seek(0) to be able to use the contents in several loops like in my code above.


Solution

  • You're attempting to loop through the contents of f twice:

    for line in f:
    
    for linez in f:
    

    ... and you can't do it that way. The second loop will exit immediately, because you already read all of the lines; there are none left to read.

    If you want to save the lines of a file and loop through them several times, use something like this:

    all_lines = f.readlines()