Python readlines不返回任何东西? [英] Python readlines not returning anything?

查看:279
本文介绍了Python readlines不返回任何东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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()每次都只返回一个空列表.

For some reason though, current.readlines() just returns an empty list every time.

代码中可能存在愚蠢的错误或错字,但我只是找不到.预先感谢.

There is probably a stupid mistake or typo in the code, but I just cannot find it. Thanks in advance.

推荐答案

您已经读取文件 ,并且文件指针不在文件的 end 处.则调用readlines()不会返回数据.

You read the file already, and the file pointer is not at the end of the file. Calling readlines() then will not return data.

仅读取一次文件:

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

另一种选择是在重新阅读之前先回到开头:

The other option is to seek back to the start before reading again:

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时间.

but that's just wasting CPU and I/O time.

最好的方法是尝试读取少量的 数据,或者搜索到最后,使用file.tell()缩小文件大小,然后再搜索到开始,而没有读.然后将文件用作迭代器,以防止将所有数据读取到内存中.这样,当文件很大时,您就不会产生内存问题:

The best approach would be to try and read a small amount of data, or seek to the end, take the file size by using file.tell() and then seek back to the start, all without reading. Then use the file as an iterator to prevent reading all the data into memory. That way you don't produce memory problems when the file is very large:

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不返回任何东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆