简体   繁体   English

Python中的readlines()函数

[英]readlines() function in Python

When I type the following into a .py file (using version 2, if that matters) and run, 当我在.py文件中键入以下内容(使用版本2,如果重要的话)并运行时,

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

 for line in f:

          print line

all lines of my file 'file.txt' are printed in shell. 我文件'file.txt'的所有行都打印在shell中。

When I type the following into a .py file and run, 当我在.py文件中键入以下内容并运行时,

 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: 如果进入shell中的命令行,然后输入以下内容,则输出为:

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

Finally, when I start in shell and type, f=open('file.txt','r') 最后,当我从外壳开始输入时,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? 为什么“打印行”从.py文件工作,但“ f.readlines()”却给出空输出? Why does an additional f.readlines() in the shell command line then give [] after the program was run? 为什么在运行程序后,shell命令行中的附加f.readlines()然后给出[]?

The issue you are seeing is that you expect every call in Python to print something. 您看到的问题是您希望Python中的每个调用都能打印出一些内容。 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. 交互式Python shell的行为使它可以打印函数调用的返回值。

The correct way of having the result printed is using print : print结果的正确方法是使用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. 如果是这样,则第一个for循环会将您带到文件末尾。 You need to begin again at the beginning of the file to get the desired output with the following calls to f.readlines() . 您需要从文件开头重新开始,以通过对f.readlines()的以下调用获得所需的输出。 to do this in python, you would use f.seek(0) to bring you back to the beginning of the file. 要在python中执行此操作,可以使用f.seek(0)将您带回到文件的开头。 You will need to do this in between every f.readlines() or for loop that iterates through a file. 您将需要在每个f.readlines()之间或遍历文件的for循环之间执行此操作。 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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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