【问题标题】:Python readlines not returning anything?Python readlines 不返回任何内容?
【发布时间】:2015-05-06 13:21:28
【问题描述】:

我有以下代码:

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

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

【问题讨论】:

    标签: python file python-3.x


    【解决方案1】:

    已经读取了文件,而文件指针不在文件的结尾。调用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)
    

    【讨论】:

      【解决方案2】:

      当您执行current.read() 时,您使用文件的内容,因此后续的current.readlines() 返回一个空列表。

      Martijn Pieters 的代码是必经之路。

      或者,您可以在readlines() 之前使用current.seek(0) 倒退到文件的开头,但这会不必要地复杂。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多