Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > parse text files in a directory?

Reply
Thread Tools

parse text files in a directory?

 
 
jo3c
Guest
Posts: n/a
 
      01-02-2008
hi everybody
im a newbie in python, i have a question

how do u parse a bunch of text files in a directory?

directory: /dir
files: H20080101.txt ,
H20080102.txt,H20080103.txt,H20080104.txt,H2008010 5.txt etc......

i already got a python script to read and insert a single text files
into a postgres db.

is there anyway i can do it in a batch, cause i got like 2000 txt
files.

thanks in advance

joe
 
Reply With Quote
 
 
 
 
Tim Chase
Guest
Posts: n/a
 
      01-02-2008
jo3c wrote:
> hi everybody
> im a newbie in python, i have a question
>
> how do u parse a bunch of text files in a directory?
>
> directory: /dir
> files: H20080101.txt ,
> H20080102.txt,H20080103.txt,H20080104.txt,H2008010 5.txt etc......
>
> i already got a python script to read and insert a single text files
> into a postgres db.
>
> is there anyway i can do it in a batch, cause i got like 2000 txt
> files.


>>> import os
>>> for filename in os.path.listdir(directory):

.... if is_interesting(filename):
.... do_something(filename)

you'll have to implement is_interesting() to catch filenames
you're interested in and you've already implemented the
do_something() body.

You might want to look at the "glob" module which allows for easy
filespec testing and name expansion for your "H*.txt" format:

for filename in glob.glob('H*.txt'):
do_something(filename)

If they're in subdirectories, you may want to investigate the
os.walk() generator which will walk the directory tree and allow
you to do something with the files:

for path, dirs, files in os.walk(directory):
for filename in files:
filename = os.sep.join(path, filename)
if is_interesting(filename):
do_something(filename)

-tkc






 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
optparse: parse v. parse! ?? 7stud -- Ruby 3 02-20-2008 05:20 AM
How to parse out specific data in text files and plugs into thespreadsheet cyrusgreats@gmail.com Perl Misc 17 12-15-2007 11:07 PM
how i can extract text from the PDF files,power point files,Ms word files? crazyprakash Java 4 10-30-2005 10:17 AM
How to parse a string like C program parse the command line string? linzhenhua1205@163.com C Programming 19 03-15-2005 07:41 PM
Text files read multiple files into single file, and then recreate the multiple files googlinggoogler@hotmail.com Python 4 02-13-2005 05:44 PM



Advertisments