V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
XIVN1987
V2EX  ›  Python

file.read()如何遍历

  •  
  •   XIVN1987 · 2018-11-17 11:52:49 +08:00 · 2428 次点击
    这是一个创建于 1959 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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()能不能做成上面那种遍历的形式??

    8 条回复    2018-11-17 14:01:57 +08:00
    cominghome
        1
    cominghome  
       2018-11-17 12:00:26 +08:00
    天天 pythonic,你知道不知道 pythonic 是啥意思?
    少点折腾都想想业务不好吗
    XIVN1987
        2
    XIVN1987  
    OP
       2018-11-17 12:03:43 +08:00
    @cominghome
    今天周末,,不需要想业务( ̄、 ̄)
    hanxiV2EX
        3
    hanxiV2EX  
       2018-11-17 12:20:19 +08:00 via Android
    用 with 可以少写一行 close
    GoLand
        4
    GoLand  
       2018-11-17 12:38:18 +08:00   ❤️ 1
    XIVN1987
        5
    XIVN1987  
    OP
       2018-11-17 12:58:21 +08:00 via Android
    想到一种比较复杂的方法

    from functools import partial

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

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

    这样的话简洁好多,,可惜 Python 不支持
    AX5N
        7
    AX5N  
       2018-11-17 13:41:54 +08:00
    把 break 的条件放到 while 上,就能去掉 break 了
    cyrbuzz
        8
    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)

    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2416 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 15:57 · PVG 23:57 · LAX 08:57 · JFK 11:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.