Ths*_*aek 1 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)
Run Code Online (Sandbox Code Playgroud)
该文件包含:
#Nothing to see here
#Just temporary data
PS__CURRENT_INST__instance.12
PS__PREV_INST__instance.16
PS__DEFAULT_INST__instance.10
Run Code Online (Sandbox Code Playgroud)
但是出于某种原因,current.readlines()每次只返回一个空列表.
代码中可能存在一个愚蠢的错误或拼写错误,但我找不到它.提前致谢.
Mar*_*ers 11
您已经读取了文件,文件指针不在文件的末尾.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)
Run Code Online (Sandbox Code Playgroud)
另一种选择是在再次阅读之前重新开始:
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)
Run Code Online (Sandbox Code Playgroud)
但这只是浪费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)
Run Code Online (Sandbox Code Playgroud)
要么
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)
Run Code Online (Sandbox Code Playgroud)
当您这样做时current.read(),您会消耗文件的内容,因此后续操作current.readlines()会返回一个空列表。
Martijn Pieters 的代码就是正确的选择。
current.seek(0)或者,您可以在之前使用 倒回到文件的开头readlines(),但这不必要地复杂。