pretty

Thursday, August 29, 2013

Traverse a directory in python

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
import os

for root, dirs, files in os.walk(rootpath):
	for filename in files:
		path = os.path.join(root, filename)
		print path

With file filtering

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
import os
import fnmatch

pattern = "*.conf"
rootpath = "/etc"
for root, dirs, files in os.walk(rootpath):
	for filename in fnmatch.filter(files, pattern):
		path = os.path.join(root, filename)
		print path
Python 2.7 documentation on os