【问题标题】:How to read file chunk by chunk? [duplicate]如何逐块读取文件? [复制]
【发布时间】:2021-08-20 20:26:00
【问题描述】:

我有 test.txt 文件:

"hi there 1, 3, 4, 5"

当我使用 python 读取它时,如何逐部分读取它,例如首先我读取前 4 个字符,然后读取接下来的 4 个字符,然后读取所有左侧。

我的代码在这里:

with open(file, 'r', encoding='utf-8', errors='ignore') as f:
             lines = f.read(4)

使用此代码我只能读取前 4 个字符,知道我可以在循环中准备好每 4 个字符直到读取所有字符吗?

【问题讨论】:

  • 你到底想做什么?

标签: python python-3.x file


【解决方案1】:

这能回答你的问题吗?

with open('z.txt', 'r', encoding='utf-8', errors='ignore') as f:
    lines = f.read()
    x=len(lines)//4
    print(x)
    with open('z.txt', 'r', encoding='utf-8', errors='ignore') as c:
        for times in range(x+1):
            l=c.read(4)
            print(l)

输出:

5
"hi
ther
e 1,
 3,
4, 5
"

【讨论】:

    【解决方案2】:

    您可以使用iter 的两个参数形式,它接受一个可调用值和一个标记值。它会反复调用callable,直到收到sentinel值。

    >>> from functools import partial
    >>> with open('test.txt') as f:
    ...     for chunk in iter(partial(f.read, 4), ''):
    ...         print(repr(chunk), len(chunk))
    ...
    '"hi ' 4
    'ther' 4
    'e 1,' 4
    ' 3, ' 4
    '4, 5' 4
    '"\n\n' 3
    

    【讨论】:

      【解决方案3】:

      使用while 循环

        with open(file, 'r', encoding='utf-8', errors='ignore') as f:
                       lines = f.read()
                       total_length = len(lines)
                       var = 4
                       print(lines)
                       while var <= total_length :
                           print(lines[(var-4):var])
                           var += 4
                       else:
                           print(lines[(var-4):var])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-06
        • 2012-06-22
        • 2022-01-25
        • 2020-09-05
        • 1970-01-01
        • 2021-09-26
        • 2012-09-05
        相关资源
        最近更新 更多