[Tutor] files in a directory

Liam Clarke cyresse at gmail.com
Sun Jan 30 09:41:19 CET 2005


Hey Kumar, 

You redirect stdin a lot.

try this.

import os

def parse(filename):
   try:
     f1 = open(filename,'r')
   except IOError:
     return
     #Listdir returns a list of files and sub-dirs, and an attempt
     #to open a sub-dir raises an IOError.

   int = f1.read().split('\n')

   my_vals  = intParser(int)

   intParser return a list
   f2  = open('myvalues.txt','a')
   # I appended this one, cos I'm assuming you wanted
   #all the input in one file. For sep files, I'd just do 
   #something like f2  = open(filename+'.txt','w')

   for line in my_vals:
     f2.write(line)
     f2.write('\n')

   f2.close()
   return

kx = os.listdir('your_directory_here')

for filename in kx:
     parse(kx)


So yeah, os.listdir() is your friend. Just remember the try - IOError
block to catch sub-dirs.

Standard disclaimer -

prolly is a better, cleaner, simpler way to do it. But, this way works. 
And it's better (imao) than redirecting stdin all the time.

Regards,

Liam Clarke

On Sun, 30 Jan 2005 00:03:18 -0800 (PST), kumar s <ps_python at yahoo.com> wrote:
> Hello.
> 
> I wrote a parser to parse spot intensities. The input
> to this parser i am giving one single file
> 
> f1 = open('my_intensity_file.dml','r')
> int = f1.read().split('\n')
> 
> my_vals  = intParser(int)
> 
> intParser return a list
> f2  = open('myvalues.txt','w')
> for line in my_vals:
>      f2.write(line)
>      f2.write('\n')
> 
> f2.close()
> 
> The problem with this approach is that, i have to give
> on file per a run. I have 50 files to pare and i want
> to do that in one GO.  I kepy those 50 files in one
> directory. Can any one suggest an approach to automate
> this process.
> 
> I tried to use f1 = stdin(...) it did not work. i dont
> know , possible is that i am using incorrect syntax.
> 
> Any suggestions.
> 
> Thank you.
> K
> 
> 
> __________________________________
> Do you Yahoo!?
> All your favorites on one personal page – Try My Yahoo!
> http://my.yahoo.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


--  
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only ba  sic human duty, to take the consequences.


More information about the Tutor mailing list