首页 文章

如何迭代给定目录中的文件?

提问于
浏览
327

我需要遍历给定目录中的所有 .asm 文件并对它们执行一些操作 .

如何以有效的方式完成?

6 回答

  • 2

    原始答案:

    for filename in os.listdir(directory):
        if filename.endswith(".asm") or filename.endswith(".py"): 
            # print(os.path.join(directory, filename))
            continue
        else:
            continue
    

    Python 3.6版本的上述答案,使用os - 假设您在名为 directory_in_str 的变量中将目录路径作为 str 对象:

    directory = os.fsencode(directory_in_str)
    
    for file in os.listdir(directory):
        filename = os.fsdecode(file)
        if filename.endswith(".asm") or filename.endswith(".py"): 
            # print(os.path.join(directory, filename))
            continue
        else:
            continue
    

    或者递归,使用pathlib

    from pathlib import Path
    
    pathlist = Path(directory_in_str).glob('**/*.asm')
    for path in pathlist:
        # because path is object not string
        path_in_str = str(path)
        # print(path_in_str)
    
  • 89

    这将迭代所有后代文件,而不仅仅是目录的直接子项:

    import os
    
    for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            #print os.path.join(subdir, file)
            filepath = subdir + os.sep + file
    
            if filepath.endswith(".asm"):
                print (filepath)
    
  • 9

    您可以尝试使用glob模块

    import glob
    
    for filepath in glob.iglob('my_dir/*.asm'):
        print(filepath)
    
  • 488

    Python 3.4及更高版本在标准库中提供pathlib . 你可以这样做:

    from pathlib import Path
    
    asm_pths = [pth for pth in Path.cwd().iterdir()
                if pth.suffix == '.asm']
    

    或者,如果您不喜欢列表推导:

    asm_paths = []
    for pth in Path.cwd().iterdir():
        if pth.suffix == '.asm':
            asm_pths.append(pth)
    

    Path 对象可以很容易地转换为字符串 .

  • 89

    我对这个实现还不是很满意,我想要一个自定义构造函数来执行 DirectoryIndex._make(next(os.walk(input_path))) ,这样你就可以传递你想要文件列表的路径了 . 编辑欢迎!

    import collections
    import os
    
    DirectoryIndex = collections.namedtuple('DirectoryIndex', ['root', 'dirs', 'files'])
    
    for file_name in DirectoryIndex(*next(os.walk('.'))).files:
        file_path = os.path.join(path, file_name)
    
  • 1

    以下是我在Python中迭代文件的方法:

    import os
    
    path = 'the/name/of/your/path'
    
    folder = os.fsencode(path)
    
    filenames = []
    
    for file in os.listdir(folder):
        filename = os.fsdecode(file)
        if filename.endswith( ('.jpeg', '.png', '.gif') ): # whatever file types you're using...
            filenames.append(filename)
    
    filenames.sort() # now you have the filenames and can do something with them
    

    NONE OF THESE TECHNIQUES GUARANTEE ANY ITERATION ORDERING

    是的,超级难以预料 . 请注意,我对文件名进行排序,如果文件的顺序很重要,即对于视频帧或时间相关的数据收集,这很重要 . 务必将索引放在文件名中!

相关问题