Reputation: 63
Is it possible to use both read() and readline() on one text file in python?
When I did that, it will only do the first reading function.
file = open(name, "r")
inside = file.readline()
inside2 = file.read()
print(name)
print(inside)
print(inside2)
The result shows only the inside
variable, not inside2
.
Upvotes: 6
Views: 2527
Reputation: 78554
Yes you can.
file.readline()
reads a line from the file (the first line in this case), and then file.read()
reads the rest of the file starting from the seek position, in this case, where file.readline()
left off.
You are receiving an empty string with f.read()
probably because you reached EOF - End of File immediately after reading the first line with file.readline()
implying your file only contains one line.
You can however return to the start of the file by moving the seek position to the start with f.seek(0)
.
Upvotes: 2
Reputation: 20366
Reading a file is like reading a book. When you say .read()
, it reads through the book until the end. If you say .read()
again, well you forgot one step. You can't read it again unless you flip back the pages until you're at the beginning. If you say .readline()
, we can call that a page. It tells you the contents of the page and then turns the page. Now, saying .read()
starts there and reads to the end. That first page isn't included. If you want to start at the beginning, you need to turn back the page. The way to do that is with the .seek()
method. It is given a single argument: a character position to seek to:
with open(name, 'r') as file:
inside = file.readline()
file.seek(0)
inside2 = file.read()
There is also another way to read information from the file. It is used under the hood when you use a for
loop:
with open(name) as file:
for line in file:
...
That way is next(file)
, which gives you the next line. This way is a little special, though. If file.readline()
or file.read()
comes after next(file)
, you will get an error that mixing iteration and read methods would lose data. (Credits to Sven Marnach for pointing this out.)
Upvotes: 7