【问题标题】:Delete every 5th byte of a large file with Python使用 Python 删除大文件的每 5 个字节
【发布时间】:2020-08-31 17:12:31
【问题描述】:

我尝试使用此代码删除大文件的每 5 个字节,但它不起作用:

from io import BytesIO

f = open("data.bin", 'rb')
chunk = f.read(5)
while chunk:
    # Truncate the chunk.
    BytesIO(chunk).truncate(5 - 1)
    chunk = f.read(5)
f.close()

怎么了?

【问题讨论】:

  • 您的文件以只读方式打开。为什么您希望文件更改?

标签: python byte truncate


【解决方案1】:

也许这会有所帮助?

from pathlib import Path

source_path = Path("source_file.txt")
destination_path = Path("temporary_file.txt")
with source_path.open("rb") as source:
    with destination_path.open("wb") as destination:
        bytes = source.read(5)
        while len(bytes) > 0:
            # print(f"{bytes} => {bytes[:4]}")
            destination.write(bytes[:4])
            bytes = source.read(5)

destination_path.rename(source_path)

【讨论】:

猜你喜欢
  • 2015-04-09
  • 2014-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 2019-12-28
  • 2017-06-25
  • 2020-04-10
相关资源
最近更新 更多