你读的文件 已经 和文件指针不是在 末尾 的文件。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)