【8.5】生成器如何读取大文件

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 
 5 def MyReadLines(f, newline):
 6     buf = ''
 7     while True:
 8         while newline in buf:
 9             pos = buf.index(newline)
10             yield buf[:pos]
11             buf = buf[pos + len(newline):]
12         chunk = f.read(4096*10)
13         if not chunk:
14             # 说明已经读到了文件结尾,处理最后一条数据
15             yield buf
16             break
17         buf += chunk
18 
19 
20 with open('read_file.txt') as f:
21     for line in MyReadLines(f, '{|}'):
22         print(line)
asdjkhaskjfdhaskhd
 asdjalskhdkjashgkdyoias
 asdjaslhdiasghfou
 wiuqoxgsabjkdg
 ashdoqwhdasjdha
 as;djoqwhdohqwodhg

  文件中的数据,一行且很大

1 with open(filePath) as f:
2     for line in f:
3         print(line)
4         # Processing data

  文件数据大,但是多行

转载于:https://www.cnblogs.com/zydeboke/p/11278429.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值