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?

share|improve this question
up vote 294 down vote accepted

Original answer:

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:

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)
share|improve this answer
1  
This just seems to list the directories or files immediately under a directory. The answer by pedromateo below seems to do a recursive listing. – Jay Sheth Mar 31 '16 at 17:14
5  
Good answer! I can add that you need to import the Python "os" module with: - import os – Gabrer Feb 22 '17 at 23:52
3  
Please note that in Python 3.6 directory is expected to be in bytes and then listdir will spit out a list of filenames also in bytes data type so you cannot run endswith directly on it. This code block should be changed to 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 – Kim Stacks May 20 '17 at 4:52
2  
print(os.path.join(directory, filename)) need to be changed to print(os.path.join(directory_in_str, filename)) to get it to work in python 3.6 – Hugo Koopmans Jun 3 '17 at 21:17
    
On the third example, why not just use .rglob("*.asm") to check recursively. – EndermanAPM Nov 23 '17 at 8:27

You can try using glob module

import glob

for filename in glob.iglob('/foobar/*.asm'):
     print('/foobar/%s' % filename)
share|improve this answer

This will iterate over all descendant files, not just the immediate children of the directory:

import os

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        #print os.path.join(subdir, file)
        filepath = subdir + os.sep + file

        if filepath.endswith(".asm"):
            print (filepath)
share|improve this answer
1  
A reference for the os.walk function is found at the following: docs.python.org/2/library/os.path.html#os.path.walk – ScottMcC Jan 31 '17 at 6:51

Python 3.4 and later offer pathlib in the standard library. You could do:

from pathlib import Path

asm_pths = [pth for pth in Path.cwd().iterdir()
            if pth.suffix == '.asm']

Or if you don't like list comprehensions:

asm_paths = []
for pth in Path.cwd().iterdir():
    if pth.suffix == '.asm':
        asm_pths.append(pth)

Path objects can easily be converted to strings.

share|improve this answer

I'm not quite happy with this implementation yet, I wanted to have a custom constructor that does DirectoryIndex._make(next(os.walk(input_path))) such that you can just pass the path you want a file listing for. Edits welcome!

import collections
import os

DirectoryIndex = collections.namedtuple('DirectoryIndex', ['root', 'dirs', 'files'])

for file_name in DirectoryIndex(*next(os.walk('.'))).files:
    file_path = os.path.join(path, file_name)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.