Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can read() and readline() be used together?

Tags:

python

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.

like image 202
JoanLamrack Avatar asked Oct 11 '16 13:10

JoanLamrack


1 Answers

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

like image 143
zondo Avatar answered Oct 24 '22 08:10

zondo