如何在Python中复制文件?


当前回答

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

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

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

其他回答

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

copy2(src,dst)通常比copyfile(src,gst)更有用,因为:

它允许dst是一个目录(而不是完整的目标文件名),在这种情况下,src的基本名称用于创建新文件;它在文件元数据中保留了原始的修改和访问信息(mtime和atime)(不过,这会带来一些开销)。

下面是一个简短的示例:

import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext

从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将覆盖目标位置的任何内容

在Python中,可以使用

梭式组件操作系统模块子流程模块


import os
import shutil
import subprocess

1) 使用shutil模块复制文件

shutil.copyfile签名

shutil.copyfile(src_file, dest_file, *, follow_symlinks=True)

# example    
shutil.copyfile('source.txt', 'destination.txt')

shutil.copy签名

shutil.copy(src_file, dest_file, *, follow_symlinks=True)

# example
shutil.copy('source.txt', 'destination.txt')

shutil.copy2签名

shutil.copy2(src_file, dest_file, *, follow_symlinks=True)

# example
shutil.copy2('source.txt', 'destination.txt')  

shutil.copyfileobj签名

shutil.copyfileobj(src_file_object, dest_file_object[, length])

# example
file_src = 'source.txt'  
f_src = open(file_src, 'rb')

file_dest = 'destination.txt'  
f_dest = open(file_dest, 'wb')

shutil.copyfileobj(f_src, f_dest)  

2) 使用os模块复制文件

os.popen签名

os.popen(cmd[, mode[, bufsize]])

# example
# In Unix/Linux
os.popen('cp source.txt destination.txt') 

# In Windows
os.popen('copy source.txt destination.txt')

os.system签名

os.system(command)


# In Linux/Unix
os.system('cp source.txt destination.txt')  

# In Windows
os.system('copy source.txt destination.txt')

3) 使用子流程模块复制文件

subprocess.call签名

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.call('cp source.txt destination.txt', shell=True) 

# In Windows
status = subprocess.call('copy source.txt destination.txt', shell=True)

subprocess.check_output签名

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

# example (WARNING: setting `shell=True` might be a security-risk)
# In Linux/Unix
status = subprocess.check_output('cp source.txt destination.txt', shell=True)

# In Windows
status = subprocess.check_output('copy source.txt destination.txt', shell=True)

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

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

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