在Python中区分空行和文件结尾

时间:2014-11-19 20:30:13

标签: python file while-loop eof blank-line

我不断遇到的情况如下:

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()会返回一个空白字符串。

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

1 个答案:

答案 0 :(得分:1)

只需使用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循环。