file.read()如何遍历

2018-11-17 11:52:49 +08:00
 XIVN1987
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()能不能做成上面那种遍历的形式??

2444 次点击
所在节点    Python
8 条回复
cominghome
2018-11-17 12:00:26 +08:00
天天 pythonic,你知道不知道 pythonic 是啥意思?
少点折腾都想想业务不好吗
XIVN1987
2018-11-17 12:03:43 +08:00
@cominghome
今天周末,,不需要想业务( ̄、 ̄)
hanxiV2EX
2018-11-17 12:20:19 +08:00
用 with 可以少写一行 close
GoLand
2018-11-17 12:38:18 +08:00
XIVN1987
2018-11-17 12:58:21 +08:00
想到一种比较复杂的方法

from functools import partial

for line in iter(partial(open(filename, 'rb').read, 128), b''):
print(line)
XIVN1987
2018-11-17 13:02:17 +08:00
要是 str 和 bytes 支持按长度分割就好了,,那样的话就可以写成类似:

for line in open(filename, 'rb').read().countsplit(128): print(line)

这样的话简洁好多,,可惜 Python 不支持
AX5N
2018-11-17 13:41:54 +08:00
把 break 的条件放到 while 上,就能去掉 break 了
cyrbuzz
2018-11-17 14:01:57 +08:00
考虑复用的话,写成类怎么样?虽然内部还是第一种写法。
```
class MyOpenFile:

def __init__(self, *args):
self.file = open(*args)

def read(self, chunk_size):
while 1:
line = self.file.read(chunk_size)
if not line:
break
yield line

def __del__(self):
self.file.close()

file = MyOpenFile(filename, 'rb')
for i in file.read(128):
print(i)

```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/508740

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX