如何在Python中复制文件?


当前回答

有两种在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')

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

其他回答

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

或者就像我做的那样,

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

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

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

您可以使用os.link创建文件的硬链接:

os.link(source, dest)

这不是一个独立的克隆,但是如果您计划只读取(而不是修改)新文件,并且其内容必须保持与原始文件相同,那么这将很好地工作。它还有一个好处,如果你想检查副本是否已经存在,你可以比较硬链接(与os.stat)而不是它们的内容。

在Linux中,命令cp带有键

cp -al

创建硬链接。因此,硬链接可被视为副本。有时,一个人需要完全这种行为(从不同的地方访问文件内容),而不需要单独的副本。

这里有一个简单的方法,不需要任何模块。这与这个答案类似,但如果它是一个不适合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.copyfileobj”的答案,它非常高效。我在不久前创建的一个工具中使用了它。我最初没有写这篇文章,但我稍微修改了一下。

def copyFile(src, dst, buffer_size=10485760, perserveFileDate=True):
    '''
    @param src:    Source File
    @param dst:    Destination File (not file path)
    @param buffer_size:    Buffer size to use during copy
    @param perserveFileDate:    Preserve the original file date
    '''
    #    Check to make sure destination directory exists. If it doesn't create the directory
    dstParent, dstFileName = os.path.split(dst)
    if(not(os.path.exists(dstParent))):
        os.makedirs(dstParent)

    # Optimize the buffer for small files
    buffer_size = min(buffer_size,os.path.getsize(src))
    if(buffer_size == 0):
        buffer_size = 1024

    if shutil._samefile(src, dst):
        raise shutil.Error("`%s` and `%s` are the same file" % (src, dst))
    for fn in [src, dst]:
        try:
            st = os.stat(fn)
        except OSError:
            # File most likely does not exist
            pass
        else:
            # XXX What about other special files? (sockets, devices...)
            if shutil.stat.S_ISFIFO(st.st_mode):
                raise shutil.SpecialFileError("`%s` is a named pipe" % fn)
    with open(src, 'rb') as fsrc:
        with open(dst, 'wb') as fdst:
            shutil.copyfileobj(fsrc, fdst, buffer_size)

    if(perserveFileDate):
        shutil.copystat(src, dst)

Python提供了内置函数,可以使用操作系统shell实用程序轻松复制文件。

以下命令用于复制文件:

shutil.copy(src, dst)

以下命令用于复制包含元数据信息的文件:

shutil.copystat(src, dst)