如何在Python中复制文件?
当前回答
您可以使用os.link创建文件的硬链接:
os.link(source, dest)
这不是一个独立的克隆,但是如果您计划只读取(而不是修改)新文件,并且其内容必须保持与原始文件相同,那么这将很好地工作。它还有一个好处,如果你想检查副本是否已经存在,你可以比较硬链接(与os.stat)而不是它们的内容。
在Linux中,命令cp带有键
cp -al
创建硬链接。因此,硬链接可被视为副本。有时,一个人需要完全这种行为(从不同的地方访问文件内容),而不需要单独的副本。
其他回答
万一你走得这么远。答案是您需要整个路径和文件名
import os
shutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, 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将只接受字符串。
您可以使用os.system('cp nameoflegatedbyprogram/otherdirectory/')。
或者就像我做的那样,
os.system('cp '+ rawfile + ' rawdata.dat')
其中rawfile是我在程序中生成的名称。
这是一个仅限Linux的解决方案。
在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的答案。