newbie question(file-delete trailing comma)

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Feb 28 20:46:29 EST 2007


En Wed, 28 Feb 2007 08:34:29 -0300, kavitha thankaian  
<kavithapython at yahoo.co.in> escribió:

> thanks,,
>   now i have one more problem,,,
>   the strings should be seperated in an order,,,
>   some={1:'a', 2:7, 3:'c', 4:'d'}
>   i need the output to be a,c,d,7
>  before my code was:
>           field_order = [1,3,4,2]
>         for field in field_order:
>             f.writelines('\"%s\",' % someprt[field] )
>  do you have an idea now how should it look like???

Proceed in small steps. First get the data you need to write, then, format  
them and build a single line, then write the new line onto the file.

some = {1:'a', 2:7, 3:'c', 4:'d'}
# i need the output to be a,c,d,7
field_order = [1,3,4,2]
row = []
for field in field_order:
     row.append(some[field])
# row contains ['a', 'c', 'd', 7]
# convert to string
row = ['%s' % item for item in row]
### alternative: convert to string, with "" around each value
##row = ['"%s"' % item for item in row]
# make a single line, using "," as separator
line = ','.join(row)
# write to file
f.write('%s\n' % line)

-- 
Gabriel Genellina




More information about the Python-list mailing list