[Tutor] Reading and Writing

Erik Price erikprice@mac.com
Thu, 29 Aug 2002 11:06:03 -0400


On Thursday, August 29, 2002, at 12:55  PM, Nicole Seitz wrote:

> infile = 
> open("C:\WINDOWS\Desktop\python_scripts\html\ez-z.html").read()
>  outFile = open("C:\WINDOWS\Desktop\python_scripts\info\ez-z.txt","w")
>
> But there's not only one file to open, there are about 20, all of them 
> in the
> same directory. My question now is:
>
> Is it possible to have the program open each of the files in this 
> directory
> and for each input file, create an output file with a proper name(what 
> I mean
> is this: for ez-a.htm I like to have ez-a.txt, and so on), so that I 
> have to
> run my program only one time?

Sure.  Write your script such that it loops through each file in your 
target directory and performs the work you need done on each file.  A 
simple way to do that is to read all of the files in a directory into a 
list, then loop over the list and perform the work to each file in the 
list.  The following code should give you an idea of how to do it, but 
you might want to add some code that ensures that only certain files 
are acted upon (based on filename, for instance -- you can do this with 
the "fnmatch" module):

<code>

import os.path

htmlDirectory = ""		# place the path to your read directory between the 
quotes
txtDirectory = ""			# place the path to your write directory between 
the quotes
os.chdir(htmlDirectory)

for file in os.listdir():
   nosuffix = file.split('.')[0]
   infile = open(file).read()
   outfile = open(txtDirectory + nosuffix + '.txt', 'w')

</code>

This will open each file in the target directory for reading, then open 
a similarly-named file in another directory (the difference is that it 
should have the suffix ".txt" instead of ".html") for writing.  Note 
that this code doesn't actually do the writing of the first file, I 
didn't include that because this is just a different version of the 
code you already posted, and that code didn't have the writing part 
either.  So you still have to implement the writing of data to the 
outfile.


HTH,



Erik

PS: if someone knows of a more efficient solution that doesn't use 
os.chdir() I would be very interested in hearing about it -- it seems 
that using os.chdir() is overkill for this but maybe not?




--
Erik Price

email: erikprice@mac.com
jabber: erikprice@jabber.org