Python,如何从文件中读取字节并保存? [关闭]

您所在的位置:网站首页 python打开mp3文件 Python,如何从文件中读取字节并保存? [关闭]

Python,如何从文件中读取字节并保存? [关闭]

2023-03-21 19:44| 来源: 网络整理| 查看: 265

回答问题

我想从文件中读取字节,然后将这些字节写入另一个文件,然后保存该文件。

我该怎么做呢?

Answers

以下是如何使用 Python 中的基本文件操作来完成此操作。这将打开一个文件,将数据读入内存,然后打开第二个文件并将其写出。

in_file = open("in-file", "rb") # opening for [r]eading as [b]inary data = in_file.read() # if you only wanted to read 512 bytes, do .read(512) in_file.close() out_file = open("out-file", "wb") # open for [w]riting as [b]inary out_file.write(data) out_file.close()

我们可以通过使用with键盘来处理关闭文件来更简洁地做到这一点。

with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file: out_file.write(in_file.read())

如果您不想将整个文件存储在内存中,则可以将其分段传输。

chunk_size = 4096 # 4 KiB with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file: while True: chunk = in_file.read(chunk_size) if chunk == b"": break # end of file out_file.write(chunk)


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3