在我的代码中,我能够在目录中搜索具有特定名称的文件。我如何编辑代码,以便它首先搜索名称以“output”一词结尾的文件夹。在下面的代码中,当我尝试包含注释掉的行时,整个事情拒绝运行。对我所缺少的任何帮助将不胜感激
def test():
file_paths = []
filenames = []
for root, dirs, files in os.walk('/Users/Bashe/Desktop/121210 p2/'):
for file in files:
#if re.match("output", file):
if re.match("Results",file):
file_paths.append(root)
filenames.append(file)
return file_paths, filenames
最佳答案
要搜索名称以“output”结尾的文件夹中的文件:
for dirpath, dirs, files in os.walk(rootdir):
if not dirpath.endswith('output'):
continue # look in the next folder
# search files
for file in files: ...
如果您甚至不想访问任何不以 "output"
结尾的目录:
if not rootdir.endswith('output'):
return # do not visit it at all
for dirpath, dirs, files in os.walk(rootdir):
assert dirpath.endswith('output')
dirs[:] = [d for d in dirs if d.endswith('output')] # edit inplace
# search files
for file in files: ...
关于python - 在python中根据名称输入文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20087571/