Search code examples
pythonfiletextloading

Python: read mode. Loading into lists (with a for loop) and using the read() method in a seperate code block


I was testing multiple scenarios of this code and wanted to understand the reason Python is behaving this way. Both scenarios are the same code but the code blocks are in inverse order.

#Peach is written in this .txt file
inputFile = open("C:\\...\\filename.txt", 'r')

Scenario 1: This code correctly prints the list but prints False at the end even though "Peach" is in the .txt file

#Loading into lists
myList = []

#For each line in the file
for line in inputFile:  
    #Add the line to myList, stripping out whitespace
    myList.append(line.strip()) 

print(myList)


if "Peach" in inputFile.read():
    print("Peach in .txt file?", True)
else:
    print("Peach in .txt file?", False)


inputFile.close()

Scenario 2: Same code, different placement. Correctly prints True but will print out an empty list.

if "Peach" in inputFile.read():
    print("Peach in .txt file?", True)
else:
    print("Peach in .txt file?", False)


#Loading into lists
myList = []
#For each line in the file
for line in inputFile:  
    #Add the line to myList, stripping out whitespace
    myList.append(line.strip()) 

print(myList)


inputFile.close()


Solution

  • Python read function will advance the position in the file after read operation, in your first code example, you iterated over content in the for loop, so by the time you reached the if statement, the read position is already at the end of the file, no peach there!

    In the second example, you read the file, advancing the position to the end of the file, so when you iterated over the file to build the list, read has nothing to add.

    place inputFile.seek(0, 0) to reposition at the beginning of the file before attempting the second block of code!

    read more here on behaviour of read: https://pscustomobject.github.io/python/Python-Reset-Read-Write-Position/