HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How can I iterate over files in a given directory?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
directoryhowfilesoveriteratecangiven

Problem

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?

Solution

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)


Original answer:
import os

for filename in os.listdir("/path/to/dir/"):
if filename.endswith(".asm") or filename.endswith(".py"):
# print(os.path.join(directory, filename))
continue
else:
continue

Context

Stack Overflow Q#10377998, score: 1324

Revisions (0)

No revisions yet.