-2

Contents of file2.txt:

zalgoalpha
beta

My code:

file = open("file2.txt", "r", encoding = "utf-8")
print(file.read())
print(file.read().find("beta"))

Why does the second print convey "-1" ("beta" doesn't exist), even though it's right in the file, at index 11?

GT 77
  • 448
  • 5
  • 12
  • 1
    You've already read _all_ of the file's data the first time you called `file.read`. The next time `file.read` is called, there is no data left to return, so `file.read` returns an empty string. Thus, `str.find` will, indeed, return `-1`. – Christian Dean Mar 24 '18 at 19:33

3 Answers3

4

Because you've already consumed the file object on the previous line. The file pointer has nothing left to read

Try this

with open("file2.txt", "r", encoding = "utf-8") as file:
    content = file.read()
    print(content) 
    print(content.find("beta"))

This way of reading files prevents you from forgetting to close a file, too

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    Just to add a bit more info: The way @cricket_007 recommends opening your file OP, uses the _context manger statement_ `with`. You can read more about `with` and context managers in general [here](http://book.pythontips.com/en/latest/context_managers.html). – Christian Dean Mar 24 '18 at 19:39
3

When you call file.read, it moves the cursor to the end of the file, therefore when you call it the second time to find "beta" it will return -1

You can fix this by doing

file.seek(0)

before you read the file the second time. Alternatively, save the contents of the file into a variable

contents = file.read()

then you can do what you did before

print(contents)
print(contents.find("beta")
dangee1705
  • 3,445
  • 1
  • 21
  • 40
0

As written in the Python documentation:

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ('').

Which basically means you just read the content of the file and reached the end of file. you can do something like that:

with open("file2.txt", "r", encoding = "utf-8") as text_file:
    text = file.read()
    print(text)
    print(text.find("beta"))