简体   繁体   English

readline()仅读取第一行

[英]readline() only reading the first line

I'm trying to read multiple lines in a file and it doesn't seem to work when I assigned my readline() method to a variable. 我正在尝试读取文件中的多行,但是当我将readline()方法分配给变量时,它似乎不起作用。 It keeps printing the first line. 它继续打印第一行。 It only seems to work when I don't assign it to a variable. 仅当我未将其分配给变量时,它才似乎有效。 Any ideas? 有任何想法吗?

I'm using Python 3.6.2. 我正在使用Python 3.6.2。 Here is my code: 这是我的代码:

# This is it not working ( I omitted the 'gradesfile_path' variable)

gradesfile = open(gradesfile_path,'r')
readgrades = gradesfile.readline()

print(readgrades)
print(readgrades)

# This is working when I don't call the variable

print(gradesfile.readline())
print(gradesfile.readline())
print(gradesfile.readline())

readline() reads a single line -- the next line in the context of the iterator returned by open() . readline()读取单个线-在由返回的迭代器的上下文中的下一open() And you are assigning the line read as variable readgrades which will always contain that line. 并且您将读取的行分配为变量readgrades ,它将始终包含该行。

Perhaps you meant to assign the method to a variable and call that variable instead: 也许您打算将方法分配给变量并调用该变量:

readgrades = gradesfile.readline  ##Note the absence of call

Then you can do: 然后,您可以执行以下操作:

readgrades()

当您将gradesfile.readline()分配给变量时,实际上是在读取一行并将该行存储到变量中

readline() is suppose to read the whole file as line by line, so I believe you need to keep calling it everytime you need to read a line and If you're not restricted to use readline(), then your objective can be achieved using: readline()假定逐行读取整个文件,所以我相信您需要在每次需要读取一行时都继续调用它,并且如果不限于使用readline(),那么可以实现您的目标使用:

read() :- will read the whole file at once read() :-将一次读取整个文件

readlines() :- will read the whole file and result it into python list readlines() :-将读取整个文件并将其放入python列表

with open('file_name', 'r') as file_obj:
    print file_obj.readlines()

or 要么

with open('file_name', 'r') as file_obj:
    some_var = file_obj.readlines()
    print some_var

or 要么

with open('file_name', 'r') as file_obj:
    print file_obj.read()

or 要么

with open('file_name', 'r') as file_obj:
    some_var = file_obj.read()
    print some_var

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

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