[Tutor] Something is wrong in file input output functions.

Michael Powe michael at trollope.org
Mon Jan 10 22:06:39 CET 2005


On Mon, Jan 10, 2005 at 12:15:18PM -0800, kumar s wrote:
> Dear group,
> I have written a small piece of code that takes a file
> and selects the columns that I am interested in and
> checks the value of the column on a condition (value
> that eqauls 25) and then write it the to another file.
> 
> 
> 
> Code:
> import sys
> from string import split
> import string
> print "enter the file name" ### Takes the file name###
> psl = sys.stdin.readline()  ### psl has the file
> object###

I may be wrong but it does not appear to me that you open the files
for reading/writing.  The variable psl does not contain the file
object, it contains the file name.  To create a file object, you have
to open it.  E.g.,

f = open(psl,"r")
w = open(out,"w")

Now str_psl = f.readlines()

creates an array of strings -- what you are trying to do with
psl.split? 

I don't know what sys.stdout.write returns (and I'm not looking it
up), but my guess would be something like the number of characters
written. 

As a matter of form, I suggest writing all function definitions and
then follow with execution code (input and function calls) -- makes it
easier to read and follow what you're doing.  I think it's unfortunate
that python does not allow us to put function defs at the end of the
file, so we can put execution code at the top ... but that's the way
of it.

I put my execution in a main function, and then call that.  Seems
tidier.


HTH

mp

> 
> f2 = sys.stdout.write("File name to write")
> def extCor(psl):
> ''' This function, splits the file and writes the
> desired columns to
> to another file only if the first column value equals
> 25.'''
>     str_psl = psl.split('\n')
>     str_psl = str_psl[5:]
>     for ele in range(len(str_psl)):
>         cols = split(str_psl[ele],'\t')
>         des_cols =
> cols[0]+'\t'+cols[1]+'\t'+cols[8]+'\t'+cols[9]+'\t'+cols[11]+'\t'+cols[12]+'\t'+cols[13]+'\t'+cols[15]+'\t'+cols[16]+'\t'+cols[17])
> 	if cols[0] == 25:
>             '''This condition checks if the first
> column value == 25, then it writes it to the file, if
> not then it does not'''
>             f2.write(des_cols)
>             f2.write("\n")
> 
> extCor(psl)
> 
> 
> 
> Question:
> when i give it the file name that it should parse, I
> do not get to asked the file name i am interested in
> it gives me nothing. Please help me. 
> Thanks
> K
> 
> 
> 		
> __________________________________ 
> Do you Yahoo!? 
> The all-new My Yahoo! - Get yours free! 
> http://my.yahoo.com 
>  
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list