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()