Python似乎具有复制文件(例如shutil.copy
)和复制目录的函数(例如)的功能,shutil.copytree
但我没有找到任何处理这两者的函数.当然,检查是否要复制文件或目录是微不足道的,但这似乎是一个奇怪的遗漏.
真的没有像unix cp -r
命令那样工作的标准函数,即递归支持目录和文件以及副本吗?在Python中解决这个问题最优雅的方法是什么?
tzo*_*zot 136
我建议你先调用shutil.copytree
,如果抛出异常,则重试shutil.copy
.
import shutil, errno
def copyanything(src, dst):
try:
shutil.copytree(src, dst)
except OSError as exc: # python >2.5
if exc.errno == errno.ENOTDIR:
shutil.copy(src, dst)
else: raise
Run Code Online (Sandbox Code Playgroud)
mon*_*eki 12
要在增加Tzot的和GNS答案,这里的递归复制文件和文件夹的另一种方式。(Python 3.X)
import os, shutil
root_src_dir = r'C:\MyMusic' #Path/Location of the source directory
root_dst_dir = 'D:MusicBackUp' #Path to the destination folder
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.copy(src_file, dst_dir)
Run Code Online (Sandbox Code Playgroud)
如果这是您第一次并且不知道如何递归复制文件和文件夹,我希望这会有所帮助。
小智 5
shutil.copy
并且shutil.copy2
正在复制文件。
shutil.copytree
复制一个包含所有文件和所有子文件夹的文件夹。shutil.copytree
正在使用shutil.copy2
复制文件。
所以cp -r
你所说的类比是shutil.copytree
因为cp -r
目标和复制文件夹及其文件/子文件夹,如shutil.copytree
. 没有-r
cp
像shutil.copy
和shutil.copy2
做的副本文件。