How can I iterate over files in a given directory?

前端 未结 9 726
北海茫月
北海茫月 2020-11-22 04:13

I need to iterate through all .asm files inside a given directory and do some actions on them.

How can this be done in a efficient way?

9条回答
  •  终归单人心
    2020-11-22 04:49

    Python 3.4 and later offer pathlib in the standard library. You could do:

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

    Or if you don't like list comprehensions:

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

    Path objects can easily be converted to strings.

提交回复
热议问题