我想从一个文件中读取字节,然后将这些字节写入另一个文件,并保存该文件。
我该怎么做?
以下是如何使用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)
在我的示例中,我在打开文件时使用了“b”标志('wb','rb'),因为您说您想读取字节。'b'标志告诉Python不要解释换行符,因为这可能会因操作系统而异。如果要读取文本,则省略'b'并分别使用'w'和'r'。
使用“最简单”的Python代码以一次读取整个文件。这种方法的问题是,当读取大文件时可能会耗尽内存:
ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
ofile.write(ifile.read())
ofile.close()
ifile.close()
为确保能够处理任何大小的文件而不会耗尽内存,此示例已经改进为每次读取1MB的数据块:
ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
data = ifile.read(1024*1024)
while data:
ofile.write(data)
data = ifile.read(1024*1024)
ofile.close()
ifile.close()
这个例子与上面的例子相同,但利用了 with 来创建一个上下文环境。这种方法的优点在于当退出上下文时,文件会自动关闭:
with open(input_filename,'rb') as ifile:
with open(output_filename, 'wb') as ofile:
data = ifile.read(1024*1024)
while data:
ofile.write(data)
data = ifile.read(1024*1024)
请参考以下链接:
with open("input", "rb") as input:
with open("output", "wb") as output:
while True:
data = input.read(1024)
if data == "":
break
output.write(data)