Puntino
Puntino

Reputation: 11

file.read() not working as intended in string comparison

stackoverflow.

I've been trying to get the following code to create a .txt file, write some string on it and then print some message if said string was in the file. This is merely a study for a more complex project, but even given it's simplicity, it's still not working.

Code:

import io

file = open("C:\\Users\\...\\txt.txt", "w+") #"..." is the rest of the file destination
file.write('wololo')

if "wololo" in file.read():
    print ("ok")

This function always skips the if as if there was no "wololo" inside the file, even though I've checked it all times and it was properly in there.

I'm not exactly sure what could be the problem, and I've spend a great deal of time searching everywhere for a solution, all to no avail. What could be wrong in this simple code?

Oh, and if I was to search for a string in a much bigger .txt file, would it still be wise to use file.read()?

Thanks!

Upvotes: 1

Views: 52

Answers (1)

Steinar Lima
Steinar Lima

Reputation: 7821

When you write to your file, the cursor is moved to the end of your file. If you want to read the data aferwards, you'll have to move the cursor to the beginning of the file, such as:

file = open("txt.txt", "w+")
file.write('wololo')

file.seek(0)
if "wololo" in file.read():
    print ("ok")
file.close() # Remember to close the file

If the file is big, you should consider to iterate over the file line by line instead. This would avoid that the entire file is stored in memory. Also consider using a context manager (the with keyword), so that you don't have to explicitly close the file yourself.

with open('bigdata.txt', 'rb') as ifile: # Use rb mode in Windows for reading
    for line in ifile:
        if 'wololo' in line:
            print('OK')
    else:
        print('String not in file')

Upvotes: 3

Related Questions