How can I iterate over files in a given directory?

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

    You can use glob for referring the directory and the list :

    import glob
    import os
    
    #to get the current working directory name
    cwd = os.getcwd()
    #Load the images from images folder.
    for f in glob.glob('images\*.jpg'):   
        dir_name = get_dir_name(f)
        image_file_name = dir_name + '.jpg'
        #To print the file name with path (path will be in string)
        print (image_file_name)
    

    To get the list of all directory in array you can use os :

    os.listdir(directory)
    
    0 讨论(0)
  • 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.")
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题