views:

165

answers:

2

For a given file

For ex : 11 ,345 , sdfsfsfs , 1232

i need to such above records from a file , read 11 to delimiter and strip the white space and store in the another file , similarly 345 to delimiter strip the while space and store in the file. This way i need to do for multiple rows.

so finally in the other file the data should look like

11,345,sdfsfsfs,1232

Please suggest me the way. Thanks for your help.

+2  A: 

Open the input file (1) and the output file (2) for reading and writing respectively.

file1 = open('file1', 'r')
file2 = open('file2', 'w')

Iterate over the input file, getting each line. Split the line on a comma. Then re-join the line using a comma, but first stripping the whitespace (using a list comprehension).

for line in file1:
   fields = line.split(',')
   line = ",".join([s.strip() for s in fields])
   file2.write(line + "\n")

Finally, close the input and output files.

file1.close()
file2.close()

I'm not sure of jython's capabilities when it comes to generators, so that is why I used a list comprehension. Please feel free to edit this (someone who knows jython better).

gahooa
+1. I would suggest using a generator expression instead of the list comprehension (just drop the square braces).
orip
Hi Gahooa , Thanks a lot for your help , it worked and i have slightly remodified the program filesrc = open('../demo/file/scd.csv','r+')for list in filesrc.readlines(): #split the records by the delimiter fields=list.split(',') #join them by striping the space line=','.join([s.strip() for s in fields]) # write to file the list filesrc.writelines(list.replace(list,line)+"\n")filesrc.close()But when i change it to this re write mode it write at the end of the records how can i modify so that old records are remodified.Thanksagain
kdev
how can i use the above program for reading and writing in the same file.
kdev
What do you mean "reading and writing in the same file" ?
gahooa
I mean 'r+' mode when iam doing so , its adding correct lines at the end of the original file .Thanks a lot for your help
kdev
A: 

One approach you could take would be to remove all whitespace using the string.translate function.

import string

#makes a 256 character string that will be used in the translate function
trans_table = string.maketrans('', '')

file1 = open('file1', 'r')
file2 = open('file2', 'w')

for line in file1:
    file2.write(line.translate(trans_table, string.whitespace) + '\n')

    #Or the above could be written as:
#    line = line.translate(trans_table, string.whitespace)
#    file2.write(line + '\n')

file1.close()
file2.close()
tgray