python readline返回什么类型,Python readlines不返回任何东西?

博客内容涉及Python代码中打开文件并检查是否为空的问题。代码在尝试读取文件两次时遇到问题,导致readlines()返回空列表。解决方案包括一次性读取文件内容或重新设置文件指针。建议使用更有效的方法避免多次读取,尤其是在处理大文件时,以防止内存问题。
摘要由CSDN通过智能技术生成

I have the following code:

with open('current.cfg', 'r') as current:

if len(current.read()) == 0:

print('FILE IS EMPTY')

else:

for line in current.readlines():

print(line)

The file contains this:

#Nothing to see here

#Just temporary data

PS__CURRENT_INST__instance.12

PS__PREV_INST__instance.16

PS__DEFAULT_INST__instance.10

For some reason though, current.readlines() just returns an empty list every time.

There is probably a stupid mistake or typo in the code, but I just cannot find it. Thanks in advance.

解决方案

You read the file already, and the file pointer is not at the end of the file. Calling readlines() then will not return data.

Read the file just once:

with open('current.cfg', 'r') as current:

lines = current.readlines()

if not lines:

print('FILE IS EMPTY')

else:

for line in lines:

print(line)

The other option is to seek back to the start before reading again:

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)

but that's just wasting CPU and I/O time.

The best approach would be to try and read a small amount of data, or seek to the end, take the file size by using file.tell() and then seek back to the start, all without reading. Then use the file as an iterator to prevent reading all the data into memory. That way you don't produce memory problems when the file is very large:

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)

or

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值