简体   繁体   中英

readlines() function in Python

When I type the following into a .py file (using version 2, if that matters) and run,

 f=open('file.txt','r')

 for line in f:

          print line

all lines of my file 'file.txt' are printed in shell.

When I type the following into a .py file and run,

 f=open('file.txt','r')

 f.readlines()

I get an empty output. If into the command line in shell I then type the following, the output is:

 f.readlines() 
 [] # output is just these empty brackets

Finally, when I start in shell and type, f=open('file.txt','r')

 f.readlines()

it prints all lines of my file perfectly.

Why did "print line" work from a .py file but "f.readlines()" gives empty output? Why does an additional f.readlines() in the shell command line then give [] after the program was run?

The issue you are seeing is that you expect every call in Python to print something. In reality, most of the time calls just return data of some sort or another.

It is the behaviour of the interactive Python shell that makes it print return values of function calls.

The correct way of having the result printed is using print :

f = open('file.txt','r')
print(f.readlines())

Are these commands all in a sequence? If so the first for loop takes you to the end of your file. You need to begin again at the beginning of the file to get the desired output with the following calls to f.readlines() . to do this in python, you would use f.seek(0) to bring you back to the beginning of the file. You will need to do this in between every f.readlines() or for loop that iterates through a file. This is also a question more suited for stackoverflow instead of programmers.

f=open('file.txt','r')

for line in f:

          print line
f.seek(0)

f.readlines()

hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM