gpt4 book ai didi

python - 我想使用 os.walk 迭代所有子目录,但只打印链接而不介入。如何降低复杂性?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:58:31 25 4
gpt4 key购买 nike

我有一段我一直在研究的代码,目前看起来像这样:

  def buildManifestFile(self):
manifestFile = self.createManifestFileForWriting(self.manifest_target)
symlinks = []
for subdir, dirs, files in os.walk(self.basedir, followlinks=True):
if self.isIncluded(self.includes,self.excludes,subdir[len(self.basedir):]) and not any(link in subdir for link in symlinks):
if not os.path.islink(subdir): ## symlinks should be listed as files, not followed.
manifestFile.write('%dir "' + subdir + '"\n')
else:
manifestFile.write('"' + subdir + '"\n')
symlinks.append(subdir)
continue
for fileName in files:
fileNameWithSubdir = '"' + subdir + "/" + fileName + '"\n'
if self.isIncluded(self.includes,self.excludes,fileNameWithSubdir):
manifestFile.write(fileNameWithSubdir)
self.closeManifestFile(manifestFile)

我想从本质上遍历一个目录,访问所有子目录、文件和符号链接(symbolic link),但我不想跟随符号链接(symbolic link),因为它会在我的输出中产生大量冗余。我实际上只是想将它们打印为一个文件。上面的代码似乎工作正常,但困扰我的部分是当我在具有许多符号链接(symbolic link)的目录上使用它时,它的复杂性增长得非常快。

最佳答案

os.walk 会默认列出符号链接(symbolic link),但不会遵循它们。在 os.walk tail 中循环文件夹时,看看还剩下什么。

def oswalker(path):
walked = list(os.walk(path))
toplevel = walked[0]
poss_folder = toplevel[1]
folders = walked[1:]

for folder in folders:
# symlinks will be listed in the walk folders, but are not
# present in the tail of the walk list
check = [i for i,x in enumerate(poss_folder) if x in folder[0]]
if check:
poss_folder.pop(check[0])

print "Symlinks %s", poss_folder


oswalker('.')

关于python - 我想使用 os.walk 迭代所有子目录,但只打印链接而不介入。如何降低复杂性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33310806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com