如何在Python中复制文件?


当前回答

这里有一个简单的方法,不需要任何模块。这与这个答案类似,但如果它是一个不适合RAM的大文件,那么它也可以工作:

with open('sourcefile', 'rb') as f, open('destfile', 'wb') as g:
    while True:
        block = f.read(16*1024*1024)  # work by blocks of 16 MB
        if not block:  # end of file
            break
        g.write(block)

因为我们正在编写一个新文件,所以它不会保留修改时间等。如果需要,我们可以使用os.utime。

其他回答

shutil.copy(src,dst,*,follow_symlinks=真)

Use

open(destination, 'wb').write(open(source, 'rb').read())

以读取模式打开源文件,以写入模式写入目标文件。

对于大型文件,我逐行读取文件,并将每一行读取到一个数组中。然后,一旦数组达到一定大小,就将其追加到新文件中。

for line in open("file.txt", "r"):
    list.append(line)
    if len(list) == 1000000: 
        output.writelines(list)
        del list[:]
Function Copies
metadata
Copies
permissions
Uses file object Destination
may be directory
shutil.copy No Yes No Yes
shutil.copyfile No No No No
shutil.copy2 Yes Yes No Yes
shutil.copyfileobj No No Yes No

有两种在Python中复制文件的最佳方法。

1.我们可以使用梭动模块

代码示例:

import shutil
shutil.copyfile('/path/to/file', '/path/to/new/file')

除了copyfile,还有其他可用的方法,如copy、copy2等,但copyfile在性能方面是最好的,

2.我们可以使用OS模块

代码示例:

import os
os.system('cp /path/to/file /path/to/new/file')

另一种方法是使用子流程,但它不是优选的,因为它是调用方法之一,不安全。