Looping through files in a directory
Tim Chase
python.list at tim.thechases.com
Wed Nov 10 20:28:15 EST 2010
On 11/10/10 16:46, Matty Sarro wrote:
> Short story - I have a few thousand files in a directory I
> need to parse through. Is there a simple way to loop through
> files? I'd like to avoid writing a python script that can
> parse 1 file, and have to call it a few thousand times from a
> bash script. Any input or pointers to functions that'd help
> would be very much appreciated.
Sounds like you're reaching for os.listdir()
import os
TARGET = '/path/to/wherever'
for fname in os.listdir(TARGET):
process_file(os.path.join(TARGET, fname))
or possibly glob.glob()
from glob import glob
for fname in glob(os.path.join(TARGET, '*.txt')):
process_file(fname)
-tkc
More information about the Python-list
mailing list