How can I iterate over files in a given directory?

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

    Original answer:

    import os
    
    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 version of the above answer, using os - assuming that you have the directory path as a str object in a variable called directory_in_str:

    import os
    
    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
    

    Or recursively, using 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)
    
    • Use rglob to replace glob('**/*.asm') with rglob('*.asm')
      • This is like calling Path.glob() with '**/' added in front of the given relative pattern:
    from pathlib import Path
    
    pathlist = Path(directory_in_str).rglob('*.asm')
    for path in pathlist:
         # because path is object not string
         path_in_str = str(path)
         # print(path_in_str)
    

提交回复
热议问题