我对 Python 很陌生,所以请多多包涵。我正在寻找写一些东西来将文件从一个目录复制到另一个目录。我找到了以下问题和答案:这里
在那里,我找到了这个答案:
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
后来有人添加以解决一些问题:
#!/usr/bin/python
import os
import shutil
import stat
def copytree(src, dst, symlinks = False, ignore = None):
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore(src, lst)
lst = [x for x in lst if x not in excl]
for item in lst:
s = os.path.join(src, item)
d = os.path.join(dst, item)
if symlinks and os.path.islink(s):
if os.path.lexists(d):
os.remove(d)
os.symlink(os.readlink(s), d)
try:
st = os.lstat(s)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(d, mode)
except:
pass # lchmod not available
elif os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
我知道当目标目录已经存在并且这些修订旨在处理它时, shutil.copytree() 会出现问题。
我的问题是关于我看到的符号链接和忽略参数,但不了解它们的作用以及它如何解决问题。
我能够找到下面的定义,这超出了我的想象:
symlinks(可选):此参数接受 True 或 False,具体取决于将原始链接或链接链接的元数据复制到新树中。
ignore(可选):如果给出了ignore,它必须是一个可调用的,它将接收copytree()正在访问的目录作为它的参数,以及它的内容列表,由os.listdir()返回。