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

Viewed 58

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

4 Answers

You can try this approach:

with open("","r") as f:
    data=f.read()
if data.find("Peach")>-1:
    print("Peach found in .txt file")
else:
    print("Peach not found in .txt file")

We read file and write text from .txt file in data. And we are finding "Peach" in that data. If found print found else print not found.
Or if you want to make a list of line by line then:

with open("","r") as f:
    data=f.readlines()
for dat in data:
    if dat.find("Peach")>-1:
        print("Peach found in .txt file")
        break
    else:
        print("Peach not found in .txt file")

Problem is that you try to read data from file two times

First time: "Peach" in inputFile.read()

Second time: for line in inputFile:

But after reading first time special "pointer" (which inform where to read next data) is at the end of file and next reading reads from the end of file - and it reads nothing.

You would have to close file and open again to move to the beginning.

inputFile = open(...)

# read all data from file
for line in inputFile:  
    # ... code ...

inputFile.close()

# ---

inputFile = open(...)

# read again all data from file
if "Peach" in inputFile.read():
    # ... code ...

inputFile.close()

Or you have to use inputFile.seek(0) to move to the beginning before next reading.

inputFile = open(...)

# read all data from file
for line in inputFile:  
    # ... code ...

inputFile.seek(0)  # move to the beginning of file

# read again all data from file
if "Peach" in inputFile.read():
    # ... code ...

inputFile.close()

Or you should read data only once and use data from memory.

inputFile = open(...)

text = inputFile.read()

inputFile.close()

# use as list of lines 

for line in text.splitlines():  
    # ... code ...

#myList = text.splitlines()  # shorter
#myList = text.split("\n")   # shorter

# use as full text

if "Peach" in text:
    # ... code ...

inputFile.close()

A file object can only be read once. When reading the file, Python actually uses a pointer to iterate the whole file. When you use "open", the pointer is set to the beginning of the file by default, and after reading it, the pointer is at the end of the file. So when you visit the file again, you'll get an empty string.

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/

Related