How can I iterate over files in a given directory?

前端 未结 9 727
北海茫月
北海茫月 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:09

    I really like using the scandir directive that is built into the os library. Here is a working example:

    import os
    
    i = 0
    with os.scandir('/usr/local/bin') as root_dir:
        for path in root_dir:
            if path.is_file():
                i += 1
                print(f"Full path is: {path} and just the name is: {path.name}")
    print(f"{i} files scanned successfully.")
    

提交回复
热议问题