您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python readlines不返回任何东西?

Python 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 2022/1/1 18:43:48 有279人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶