Wednesday, 15 January 2014

iterating through folders and from each use one specific file in a method python -



iterating through folders and from each use one specific file in a method python -

what want iterate through folders in directory , in each folder find file 'filex' want give method needs file name parameter open , specific value it. 'method' extract value 'filex' (the file name same in every folder).

my code looks told file want doesn't exist not case:

import os import xy rootdir =r'path' root, dirs, files in os.walk(rootdir): file in files: gain = xy.method(filex) print gain

also folders iterating through named 'folderx0', 'folderx1',..., 'folderx99', meaning have same name increasing ending numbers. nice if tell programme ignore every other folder might in 'path'. help!

os.walk returns file , directory names relative root directory gives. can combine them os.path.join:

for root, dirs, files in os.walk(rootdir): file in files: gain = xy.method(os.path.join(root, file)) print gain

see documentation os.walk details:

to total path (which begins top) file or directory in dirpath, os.path.join(dirpath, name).

to trim ignore folders named folderx, following. when doing os.walk top downwards (the default), can delete items dirs list prevent os.walk looking in directories.

for root, dirs, files in os.walk(rootdir): dir in dirs: if not re.match(r'folderx[0-9]+$', dir): dirs.remove(dir) file in files: gain = xy.method(os.path.join(root, file)) print gain

python

No comments:

Post a Comment