Python readlines 没有返回任何东西?

标签 python file python-3.x

我有以下代码:

with open('current.cfg', 'r') as current:
    if len(current.read()) == 0:
        print('FILE IS EMPTY')
    else:
        for line in current.readlines():
            print(line)

该文件包含以下内容:

#Nothing to see here
#Just temporary data
PS__CURRENT_INST__instance.12
PS__PREV_INST__instance.16
PS__DEFAULT_INST__instance.10

但是由于某些原因,current.readlines() 每次都返回一个空列表。

代码中可能存在愚蠢的错误或拼写错误,但我就是找不到。提前致谢。

最佳答案

已经读取文件,并且文件指针不在文件的末尾。调用 readlines() 将不会返回数据。

只读一次文件:

with open('current.cfg', 'r') as current:
    lines = current.readlines()
    if not lines:
        print('FILE IS EMPTY')
    else:
        for line in lines:
            print(line)

另一种选择是在再次阅读之前回到开头:

with open('current.cfg', 'r') as current:
    if len(current.read()) == 0:
        print('FILE IS EMPTY')
    else:
        current.seek(0)
        for line in current.readlines():
            print(line)

但这只是在浪费 CPU 和 I/O 时间。

最好的方法是尝试读取少量 数据,或者寻找到最后,使用file.tell() 获取文件大小,然后然后回到开始,所有没有阅读。然后将该文件用作迭代器,以防止将所有数据读入内存。这样当文件很大时就不会产生内存问题:

with open('current.cfg', 'r') as current:
    if len(current.read(1)) == 0:
        print('FILE IS EMPTY')
    else:
        current.seek(0)
        for line in current:
            print(line)

with open('current.cfg', 'r') as current:
    current.seek(0, 2)  # from the end
    if current.tell() == 0:
        print('FILE IS EMPTY')
    else:
        current.seek(0)
        for line in current:
            print(line)

关于Python readlines 没有返回任何东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28873349/

相关文章:

python - 我收到一个IndentationError。我如何解决它?

python - 如何以与 shell 无关、与语言无关的方式从命令行获取当前 Linux 进程 ID

python - 使用Django Rest Framework时如何将字段数据类型信息传递给前端?

java - 如何在Java中按行将CSV文件分割成不同的CSV文件?

python - Python:录制动态影像,但不存在动态影像时释放VideoWriter

python - 我如何在 tkinter 时使用 Work

python - 使用 mirror-api-python-cli 从 Raspberry Pi 连接到 Glass 可能出现 OAuth 错误

python xml转字符串,插入postgres

java - 如何获取本地文件的正确URI?

Python dict to select 函数运行所有这些