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

77

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

我该怎么做?

4个回答

150

以下是如何使用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)

4
问题在于如果文件很大,那么你将会使用大量的内存(例如复制一个2GB的文件!)。 - carl
2
以防其他人遇到此问题,停止条件应为:if piece == b''(空字节的双引号) 这个答案对我帮助很大,但在我整理事情时它做了一些无限循环。 - mauricio777

19

在我的示例中,我在打开文件时使用了“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)

请参考以下链接:


@MarkTolonen 哎呀!问题解决了... - Mark Evans

7
with open("input", "rb") as input:
    with open("output", "wb") as output:
        while True:
            data = input.read(1024)
            if data == "":
                break
            output.write(data)

上述代码将每次读取1KB并写入文件。这种方式可以支持非常大的文件,因为您不需要将整个文件读入内存中。

我宁愿读取至少100千字节并在另一个线程中写入以加快整个过程,使用这段代码。 - france1

5
使用open函数打开文件,该函数会返回一个文件对象,您可以使用该对象读写文件:
file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode

data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接