python出现openfile.readlines()读取内容为空的情况

如图:
在这里插入图片描述在这里插入图片描述(上面的输出和这个函数无关)

# 读取文件内容
content = openfile.read()
print(content)

# 按列表读取txt文件内容
content_se = openfile.readlines()
print(content_se)

解决办法

发现把上面代码打上注释代码就能运行了
在这里插入图片描述
在这里插入图片描述
查询资料发现:

因为在第一个read()之后,光标移到了文件的末尾

后来加入seek(0,0)

# 读取文件内容
content = openfile.read()
print(content)

# 将光标调到文件头
openfile.seek(0, 0)

# 按列表读取txt文件内容
content_se = openfile.readlines()
print(content_se)

得到正常输出结果

在这里插入图片描述

Python中,`file.readlines()` 方法会将文件的所有行一次性读取到内存中。如果文件非常大,这可能会导致内存不足的问题。为了解决这个问题,可以分批读取文件内容。以下是几种实现分批读取文件的方法: ### 方法一:使用 `readline()` 循环 ```python def read_in_chunks(file_path, chunk_size=1024): with open(file_path, 'r') as file: while True: lines = [] for _ in range(chunk_size): line = file.readline() if not line: break lines.append(line) if not lines: break yield lines # 使用示例 file_path = 'large_file.txt' for chunk in read_in_chunks(file_path, chunk_size=100): print(chunk) ``` ### 方法二:使用 `iter` 和 `islice` ```python from itertools import islice def read_in_chunks(file_path, chunk_size=1024): with open(file_path, 'r') as file: while True: lines = list(islice(file, chunk_size)) if not lines: break yield lines # 使用示例 file_path = 'large_file.txt' for chunk in read_in_chunks(file_path, chunk_size=100): print(chunk) ``` ### 方法三:使用生成器表达式 ```python def read_in_chunks(file_path, chunk_size=1024): with open(file_path, 'r') as file: while True: lines = [next(file) for _ in range(chunk_size)] if not lines: break yield lines # 使用示例 file_path = 'large_file.txt' for chunk in read_in_chunks(file_path, chunk_size=100): print(chunk) ``` 以上方法都可以实现分批读取文件内容,避免一次性将整个文件加载到内存中。根据具体需求选择合适的方法即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值