V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Nov 17, 2018 · 2939 views
    This topic created in 2721 days ago, the information mentioned may be changed or developed.
    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 replies    2018-11-17 14:01:57 +08:00
    cominghome
        1
    cominghome  
       Nov 17, 2018
    天天 pythonic,你知道不知道 pythonic 是啥意思?
    少点折腾都想想业务不好吗
    XIVN1987
        2
    XIVN1987  
    OP
       Nov 17, 2018
    @cominghome
    今天周末,,不需要想业务( ̄、 ̄)
    hanxiV2EX
        3
    hanxiV2EX  
       Nov 17, 2018 via Android
    用 with 可以少写一行 close
    GoLand
        4
    GoLand  
       Nov 17, 2018   ❤️ 1
    XIVN1987
        5
    XIVN1987  
    OP
       Nov 17, 2018 via Android
    想到一种比较复杂的方法

    from functools import partial

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

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

    这样的话简洁好多,,可惜 Python 不支持
    AX5N
        7
    AX5N  
       Nov 17, 2018
    把 break 的条件放到 while 上,就能去掉 break 了
    cyrbuzz
        8
    cyrbuzz  
       Nov 17, 2018
    考虑复用的话,写成类怎么样?虽然内部还是第一种写法。
    ```
    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)

    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   809 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 20:22 · PVG 04:22 · LAX 13:22 · JFK 16:22
    ♥ Do have faith in what you're doing.