如何在Python中复制文件?


当前回答

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

for line in open("file.txt", "r"):
    list.append(line)
    if len(list) == 1000000: 
        output.writelines(list)
        del list[:]

其他回答

您可以使用os.system('cp nameoflegatedbyprogram/otherdirectory/')。

或者就像我做的那样,

os.system('cp '+ rawfile + ' rawdata.dat')

其中rawfile是我在程序中生成的名称。

这是一个仅限Linux的解决方案。

与公认的答案类似,如果您还想确保在目标路径中创建任何(不存在的)文件夹,以下代码块可能会很有用。

from os import path, makedirs
from shutil import copyfile
makedirs(path.dirname(path.abspath(destination_path)), exist_ok=True)
copyfile(source_path, destination_path)

正如公认的答案所指出的,这些行将覆盖目标路径上存在的任何文件,因此有时在该代码块之前添加:if not path.exists(destination_path):可能会很有用。

shutil模块提供了一些对文件的高级操作。它支持文件复制和删除。

请参考下表了解您的用例。

Function Utilize
File Object
Preserve File
Metadata
Preserve
Permissions
Supports
Directory Dest.
shutil.copyfileobj
shutil.copyfile
shutil.copy2
shutil.copy

复制文件是一个相对简单的操作,如下面的示例所示,但是您应该使用shutilstdlib模块。

def copyfileobj_example(source, dest, buffer_size=1024*1024):
    """      
    Copy a file from source to dest. source and dest
    must be file-like objects, i.e. any object with a read or
    write method, like for example StringIO.
    """
    while True:
        copy_buffer = source.read(buffer_size)
        if not copy_buffer:
            break
        dest.write(copy_buffer)

如果要按文件名复制,可以执行以下操作:

def copyfile_example(source, dest):
    # Beware, this example does not handle any edge cases!
    with open(source, 'rb') as src, open(dest, 'wb') as dst:
        copyfileobj_example(src, dst)

对于小文件和仅使用Python内置程序,可以使用以下一行代码:

with open(source, 'rb') as src, open(dest, 'wb') as dst: dst.write(src.read())

对于文件太大或内存很关键的应用程序来说,这不是最佳方式,因此应该首选Swati的答案。