Python中如何遍历file.read()读取的内容?
for line in open(filename, 'rb'):
print(line)
这样写很美观,,很满意,,
但是我现在有个需求,,需要每次 print 128 个字节,,而不是一行,,这样的话就不得不用 read()来做,我想到的做法是:
file = open(filename, 'rb')
while True:
line = file.read(128)
if not line:
break
print(line)
file.close()
这样虽然能实现功能,,但感觉写法有点儿不 pythonic,不如上面的那个美观,,
请问调用 file.read()能不能做成上面那种遍历的形式??
Python中如何遍历file.read()读取的内容?
天天 pythonic,你知道不知道 pythonic 是啥意思?
少点折腾都想想业务不好吗
直接遍历 file.read() 返回的字符串就行,它就是个普通的字符串对象。
# 方法1: 直接遍历字符
with open('your_file.txt', 'r', encoding='utf-8') as f:
content = f.read()
for char in content:
print(char) # 每次处理一个字符
# 方法2: 如果需要按行遍历,直接用file对象本身
with open('your_file.txt', 'r', encoding='utf-8') as f:
for line in f: # 这才是按行遍历的标准做法
print(line.strip())
关键点:
file.read()一次性读取整个文件内容,返回一个字符串- 字符串是可迭代的,直接
for char in content就能逐个字符遍历 - 但通常我们不需要逐个字符处理,按行遍历更常见,这时直接用
for line in file_object更高效
总结:字符串怎么遍历,file.read() 的结果就怎么遍历。
今天周末,,不需要想业务( ̄、 ̄)
用 with 可以少写一行 close

想到一种比较复杂的方法
from functools import partial
for line in iter(partial(open(filename, ‘rb’).read, 128), b’’):
print(line)
要是 str 和 bytes 支持按长度分割就好了,,那样的话就可以写成类似:
for line in open(filename, ‘rb’).read().countsplit(128): print(line)
这样的话简洁好多,,可惜 Python 不支持
把 break 的条件放到 while 上,就能去掉 break 了
考虑复用的话,写成类怎么样?虽然内部还是第一种写法。<br>class MyOpenFile:<br> <br> def __init__(self, *args):<br> self.file = open(*args)<br> <br> def read(self, chunk_size):<br> while 1:<br> line = self.file.read(chunk_size)<br> if not line:<br> break<br> yield line <br><br> def __del__(self):<br> self.file.close()<br><br>file = MyOpenFile(filename, 'rb')<br>for i in file.read(128):<br> print(i)<br> <br>

