python - 在python中根据名称输入文件夹

标签 python

在我的代码中,我能够在目录中搜索具有特定名称的文件。我如何编辑代码,以便它首先搜索名称以“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/

相关文章:

Python - 基于多个过滤器搜索文件名的有效方法

Python处理csv文件

Python + winsound - 检查是否正在播放音频文件

python - 属性错误: 'NoneType' object has no attribute 'tags' - upgrade Django to 1. 6.5

python - 如何模拟类层次结构

python - 开源 Enthought Python 替代方案

python - 使用 python 仅将 csv 文件中的特定行插入到 Sqlite3 数据库中

python - 创建一个 Python User() 类,它既可以创建新用户又可以修改现有用户

python - 查询集对象不可调用 Django

python - Pandas 可以在 Google App Engine for Python 上运行吗?