在python中,如何复制文件?有哪些模块可以使用?
shutil 模组
os 模组
subprocess 模组
┌──────────────────┬────────┬───────────┬───────┬────────────────┐ │ Function │ Copies │ Copies │Can use│ Destination │ │ │Metadata│permissions│buffer │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 │ └──────────────────┴────────┴───────────┴───────┴────────────────┘
shutil.copyfile
shutil.copyfile(src_file, dest_file, *, follow_symlinks=True) # example shutil.copyfile('source.txt', 'destination.txt')
shutil.copy 复制时不设置元数据
shutil.copy(src_file, follow_symlinks=True) # example shutil.copy('source.txt', 'destination.txt')
shutil.copy2 保留元数据进行复制
shutil.copy2(src_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)
上述方法中,一般是copy2(src,dst)比copyfile(src,dst)更有用,原因如下:
简单实例代码:
import shutil shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # 需要给出完整的目标文件名 shutil.copy2('/src/file.ext', '/dst/dir') # 可以给相对路径,目标路径是 /dst/dir/file.ext
os.popen
# example # In Unix/Linux os.popen('cp source.txt destination.txt') # In Windows os.popen('copy source.txt destination.txt')
os.system
# In Linux/Unix os.system('cp source.txt destination.txt') # In Windows os.system('copy source.txt destination.txt')
3. 使用subprocess模块复制文件@H_301_19@
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, 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)
在python3.5以后,可以用以下代码对小文件(如文本文件,小的图片)进行复制
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())