如何在Python中复制文件?


当前回答

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

或者就像我做的那样,

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

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

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

其他回答

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

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

shutil有很多方法可以使用。其中之一是:

import shutil

shutil.copyfile(src, dst)

# 2nd option
shutil.copy(src, dst)  # dst can be a folder; use shutil.copy2() to preserve timestamp

将名为src的文件的内容复制到名为dst的文件中。src和dst都需要是文件的整个文件名,包括路径。目标位置必须是可写的;否则,将引发IOError异常。如果dst已经存在,则将替换它。无法使用此功能复制字符或块设备和管道等特殊文件。对于copy,src和dst是作为strs给出的路径名。

另一个shutil方法是shutil.copy2()。它类似,但保留了更多的元数据(例如时间戳)。

如果使用os.path操作,请使用copy而不是copyfile。copyfile将只接受字符串。

从Python 3.5开始,您可以对小文件(例如:文本文件、小jpegs)执行以下操作:

from pathlib import Path

source = Path('../path/to/my/file.txt')
destination = Path('../path/where/i/want/to/store/it.txt')
destination.write_bytes(source.read_bytes())

write_bytes将覆盖目标位置的任何内容

使用梭动模块。

copyfile(src, dst)

将名为src的文件的内容复制到名为dst的文件中。目标位置必须是可写的;否则,将引发IOError异常。如果dst已经存在,则将替换它。无法使用此功能复制字符或块设备和管道等特殊文件。src和dst是以字符串形式给出的路径名。

看看标准Python模块中所有文件和目录处理功能的filesys。

这里有一个简单的方法,不需要任何模块。这与这个答案类似,但如果它是一个不适合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。