How can I iterate over files in a given directory?

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

    Here's how I iterate through files in Python:

    import os
    
    path = 'the/name/of/your/path'
    
    folder = os.fsencode(path)
    
    filenames = []
    
    for file in os.listdir(folder):
        filename = os.fsdecode(file)
        if filename.endswith( ('.jpeg', '.png', '.gif') ): # whatever file types you're using...
            filenames.append(filename)
    
    filenames.sort() # now you have the filenames and can do something with them
    

    NONE OF THESE TECHNIQUES GUARANTEE ANY ITERATION ORDERING

    Yup, super unpredictable. Notice that I sort the filenames, which is important if the order of the files matters, i.e. for video frames or time dependent data collection. Be sure to put indices in your filenames though!

提交回复
热议问题