How can I iterate over files in a given directory?

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

    Since Python 3.5, things are much easier with os.scandir()

    with os.scandir(path) as it:
        for entry in it:
            if entry.name.endswith(".asm") and entry.is_file():
                print(entry.name, entry.path)
    

    Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

提交回复
热议问题