Writing a nice formatted csv file
Jon Clements
joncle at googlemail.com
Wed May 2 11:05:34 EDT 2007
On 2 May, 15:14, redcic <cedric.lou... at gmail.com> wrote:
> Hi all,
>
> I use the csv module of Python to write a file. My code is of the
> form :
>
> cw = csv.writer(open("out.txt", "wb"))
> cw.writerow([1,2,3])
> cw.writerow([10,20,30])
>
> And i get an out.txt file looking like:
> 1,2,3
> 10,20,30
>
> Whereas what I'd like to get is:
> 1, 2, 3,
> 10, 20, 30
>
> which is more readable.
>
> Can anybody help me to do so ?
How about pre-formatting the columns before hand before using
something like:
# List of formatting to apply to each column (change this to suit)
format = ['%03d', '%10s', '%10s']
data = [1, 10, 100]
print [fmt % d for fmt,d in zip(format,data)]
Results in: ['001', ' 10', ' 100']
Then write that using the CSV module.
hth
Jon.
More information about the Python-list
mailing list