4

我不断遇到的情况如下:

readFile = open("myFile.txt", "r")
while True:
    readLine = readFile.readline()
    if readLine == "":
        #Assume end of file
        break
    #Otherwise, do something with the line
    #...

问题是我正在阅读的文件包含空行。根据我已阅读的文档,file.readline()将返回"\n"在文件中找到的空白行,但这不会发生在我身上。如果我不将那个空行条件放在 while 循环中,它会无限地继续,因为readline()在文件末尾或之后执行的 a 会返回一个空白字符串。

有人可以帮我创建一个允许程序读取空行但在到达文件末尾时停止的条件吗?

4

1 回答 1

2

只需使用 for 循环:

for readLine in open("myFile.txt"):
    print(readLine); # Displayes your line contents - should also display "\n"
    # Do something more

在文件末尾自动停止。

如果你有时需要额外的一行,这样的事情可能会起作用:

with open("myFile.txt") as f:
    for line in f:
        if needs_extra_line(line):  # Implement this yourself :-)
            line += next(f)  # Add next line to this one
        print(line)

或生成您要使用的块的生成器:

def chunks(file_object):
    for line in file_object:
        if needs_extra_line(line):
            line += next(file_object)
        yield line

然后处理这些行的函数可以在该生成器上运行一个 for 循环。

于 2014-11-19T20:32:48.677 回答