如何在Python中复制文件?
当前回答
万一你走得这么远。答案是您需要整个路径和文件名
import os
shutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))
其他回答
在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)
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将只接受字符串。
万一你走得这么远。答案是您需要整个路径和文件名
import os
shutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))
使用梭动模块。
copyfile(src, dst)
将名为src的文件的内容复制到名为dst的文件中。目标位置必须是可写的;否则,将引发IOError异常。如果dst已经存在,则将替换它。无法使用此功能复制字符或块设备和管道等特殊文件。src和dst是以字符串形式给出的路径名。
看看标准Python模块中所有文件和目录处理功能的filesys。
Python提供了内置函数,可以使用操作系统shell实用程序轻松复制文件。
以下命令用于复制文件:
shutil.copy(src, dst)
以下命令用于复制包含元数据信息的文件:
shutil.copystat(src, dst)