Python中空行和文件结尾的区别

jdr*_*ers 5 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
    #...
Run Code Online (Sandbox Code Playgroud)

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

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

Rem*_*ich 3

只需使用 for 循环:

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

在文件末尾自动停止。

如果您有时需要额外的线路,类似这样的事情可能会起作用:

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)
Run Code Online (Sandbox Code Playgroud)

或者一个生成您想要使用的块的生成器:

def chunks(file_object):
    for line in file_object:
        if needs_extra_line(line):
            line += next(file_object)
        yield line
Run Code Online (Sandbox Code Playgroud)

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