[Tutor] Reading matching text files in a folder

Andrew Wilkins toodles@yifan.net
Tue, 30 Oct 2001 23:07:14 +0800


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"] #Replace filenames with the filenames whose
last 4 characters are ".txt". Use list comprehensions! Yay!

for filename in filenames: do_stuff_to_file(filename)
####################

> 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
>