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
.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With