how to open a traverse through a directory in python code example
Example 1: traverse files in directory python
import os
for dirpath, dirnames, filenames in os.walk(dir_path):
print(dirpath)
print(dirnames)
print(filenames)
import os.path
def print_it(x, dir_name, files):
print(dir_name)
print(files)
os.path.walk(your_dir, print_it, 0)
Example 2: python loop opening file from directory
basepath = "pathtodir/DataFiles/"
for filename in os.listdir(basepath):
if filename.endswith(".log"):
print(os.path.join("./DataFiles", filename))
with open(basepath + filename) as openfile:
for line in openfile:
........