How can I iterate over files in a given directory?

前端 未结 9 714
北海茫月
北海茫月 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 05:11

    You can try using glob module:

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

    and since Python 3.5 you can search subdirectories as well:

    glob.glob('**/*.txt', recursive=True) # => ['2.txt', 'sub/3.txt']
    

    From the docs:

    The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.

提交回复
热议问题