[Tutor] Reading matching text files in a folder
Andrew Wilkins
toodles@yifan.net
Tue, 30 Oct 2001 23:18:05 +0800
*Slaps himself in the face*
I forgot to include the date part after all...
----- Original Message -----
From: "Andrew Wilkins" <toodles@yifan.net>
To: "Schmidt, Allen J." <aschmidt@nv.cc.va.us>; <tutor@python.org>
Sent: Tuesday, October 30, 2001 11:07 PM
Subject: Re: [Tutor] Reading matching text files in a folder
> Hi Allen
>
>
> > I've been lurking for a while but now need some help...
> Isn't lurking fun? :)
>
> >
> > I have a program that reads a hard-coded filename and path like
> > "F:\\import\\20011030-Tue.txt"
> >
> > It works and breaks each line up into parts, strips out apostrophes and
> > inserts the fields into a MySQL database table.
> >
> > What I need to be able to do:
> > Look into the above folder (F:\\import\\) and see if there are any *.txt
> > files in it.
> > If so, pass it by name into my loop that breaks it up and does the DB
> > insert.
> > I also need access to the date (20011030) and the day (Tue) to use as
> fields
> > in the insert.
> > Then when done, rename the file by adding some prefix and suffix so it
is
> > not processed again the next day.
> >
> > AND...if there is more than one, loop through each of them in turn and
> > perform the above needed actions.
>
> Okay I'll make a couple of assumptions firstly:
> 1) All dates will always be the characters from the beginning to the first
> hyphen.
> 2) All days will be the characters proceding the first hyphen and
preceding
> the first full-stop.
>
#################### Following code not completely tested...
import os
def do_stuff_to_file(filename):
#do stuff to file here...
filenames=os.listdir("F:\\import\\") #Okay, firstly we need to get a list of
files in the directory
filenames=[filename.lower() for filename in filenames if
(filename[-4:].lower()==".txt" and filename[0]!="-")]
#Replace filenames with the filenames whose last 4 characters are ".txt" and
first 1 isn't "-". Use list comprehensions! Yay!
insert_info={}
for filename in filenames:
insert_info[filename]=(filename[:filename.index('-')],filename[filename.inde
x('-')+1:filename.index('.'))
#get the info for using in the inserts...i don't know exactly what you
want to do with them, so i'll leave that up to you.
os.rename("F:\\import\\"+filename,"F:\\import\\-"+filename) #prefix with
a hyphen
for filename in filenames: do_stuff_to_file(filename)
####################
Okay sorry about the screw-up. :(
>
> > Have not worked with files much and need some guidance. Links to
examples
> > also appreciated.
> >
> > Thanks
> >
> > Allen
>
> No worries,
> Andrew
>
> >
> > _______________________________________________
> > Tutor maillist - Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>