[Tutor] directory recursion
Jacob S.
keridee at jayco.net
Sat Sep 17 00:47:27 CEST 2005
Okay, how about this?
#############################
import os
from fnmatch import fnmatch
def simplewalkgen(toplevel):
"""Yields full paths of all the text files in all the subdirectories"""
for root,dirs,files in os.walk(toplevel):
for x in files:
ok = os.path.join(root,x)
if fnmatch(ok,"*.txt"):
yield ok
top = raw_input("What is the top level directory? ")
walker = simplewalkgen(top)
output = open("output.txt","w")
for fullpath in walker:
f = os.path.basename(fullpath)
input1 = open(fullpath,"r")
for i in range(3):
line = input1.readline()
output.write(line)
output.flush() ## Makes sure that it actually writes immediately?
input1.close()
print "Third line of %s written to output.txt successfully."%f
output.close()
######################
Jacob Schmidt
----- Original Message -----
From: "Rob Andrews" <rob.andrews at gmail.com>
To: <tutor at python.org>
Sent: Monday, September 12, 2005 9:55 AM
Subject: Re: [Tutor] directory recursion
> Thanks! That did the trick after very modest head scratching.
>
> -Rob
>
> On 9/9/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>> >
>> > What's a nice, clean way to recursively scan through directories with
>> > an arbitrary number of subdirectories?
>>
>> Hi Rob,
>>
>> You may want to look at os.walk():
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list