如何在Python中复制文件?
当前回答
从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将覆盖目标位置的任何内容
其他回答
shutil模块提供了一些对文件的高级操作。它支持文件复制和删除。
请参考下表了解您的用例。
Function | Utilize File Object |
Preserve File Metadata |
Preserve Permissions |
Supports Directory Dest. |
---|---|---|---|---|
shutil.copyfileobj | ✔ | ⅹ | ⅹ | ⅹ |
shutil.copyfile | ⅹ | ⅹ | ⅹ | ⅹ |
shutil.copy2 | ⅹ | ✔ | ✔ | ✔ |
shutil.copy | ⅹ | ⅹ | ✔ | ✔ |
目录和文件复制示例,来自Tim Golden的Python Stuff:
import os
import shutil
import tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1, "w").close ()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2
shutil.copy (filename1, filename2)
if os.path.isfile (filename2): print "Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 + ".copy"
print dirname1, "=>", dirname2
shutil.copytree (dirname1, dirname2)
if os.path.isdir (dirname2): print "Success"
万一你走得这么远。答案是您需要整个路径和文件名
import os
shutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))
这里有一个简单的方法,不需要任何模块。这与这个答案类似,但如果它是一个不适合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。
Use
open(destination, 'wb').write(open(source, 'rb').read())
以读取模式打开源文件,以写入模式写入目标文件。