模块介绍
shutil是Python自带lib中的一员,支持对文件和文件集合的一系列高阶操作。
- shutil.copyfileobj
- shutil.copyfile
- shutil.copymode
- shutil.copystat
- shutil.copy
- shutil.copy2
- shutil.ignore_patterns
- shutil.copytree
- shutil.rmtree
- shutil.move
- shutil.disk_usage
- shutil.chown
- shutil.which
- shutil.make_archive
- shutil.get_archive_formats
- shutil.register_archive_format
- shutil.unregister_archive_format
- shutil.unpack_archive
- shutil.register_unpack_format
- shutil.unregister_unpack_format
- shutil.get_unpack_formats
- shutil.get_terminal_size
模块使用
实现从src拷贝文件或文件夹到target。
注:从src拷贝到target,shutil.copytree
需要target不存在,否则会报错。
调用shutil.copytree
时底层会先调用os.makedirs(dst)
,继而引发报错。
def shutil_copy_util(src, target):
"""拷贝判断,避免重复拷贝"""
if not os.path.exists(target):
if os.path.isdir(src):
shutil.copytree(src, target)
elif os.path.isfile(src):
os.makedirs(target)
shutil.copy(src, target)
else:
if os.path.isdir(src):
dirs = glob.glob(src+'/*')
for dir_i in dirs:
subdir = os.path.basename(dir_i)
tar_dir = target+'/'+ subdir
if not os.path.exists(tar_dir):
if os.path.isdir(dir_i):
shutil.copytree(dir_i, tar_dir)
elif os.path.isfile(dir_i):
shutil.copy(dir_i, tar_dir)
elif os.path.isfile(src):
shutil.copy(src, target)
参考资料
[1] shutil — 高阶文件操作
[2] Python shutil模块