我有以下代码:
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()
每次都返回一个空列表。
代码中可能存在愚蠢的错误或拼写错误,但我就是找不到。提前致谢。
最佳答案
您已经读取文件,并且文件指针不在文件的末尾。调用 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)
关于Python readlines 没有返回任何东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28873349/