Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python readlines没有返回任何内容?_Python_File_Python 3.x - Fatal编程技术网

Python readlines没有返回任何内容?

Python readlines没有返回任何内容?,python,file,python-3.x,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__CUR

我有以下代码:

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


代码中可能有愚蠢的错误或打字错误,但我就是找不到。提前感谢。

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

Martijn Pieters的代码是正确的选择

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

您已经读取了文件,并且文件指针不在文件的末尾。然后调用
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)