[Tutor] CSV to Excel

Tim Golden mail at timgolden.me.uk
Thu Mar 17 10:27:25 CET 2011


On 16/03/2011 17:12, Susana Iraiis Delgado Rodriguez wrote:
>
> Thank you for your help!
> Once I read your comments I tried both corrections in my code, but none
> of them we're sucessful.

Ok, Susana, your problem (here) is the use of the csv module
so can I suggest we back away from your wider program and try
to help you understand the way in which that works.

Here's a really simple example of how to use the module:

<code>
import os
import csv

#
# Open a file which will automatically close once
# we're finished
#
with open ("temp.csv", "wb") as f:
   writer = csv.writer (f)

   #
   # Write to the csv file with explicit (if meaningless) strings
   #
   writer.writerow (['A', 'B', 'C'])

   list_of_stuff = ["Name", 2, 3]
   #
   # Write something which is already a list (like your filenames)
   #
   writer.writerow (list_of_stuff)


#
# Now look at the contents of the file produced
#
print open ("temp.csv").read ()

</code>


Can you run that and make sure that it produces the .csv format
which you'd expect. The output should look something like this:

A,B,C
Name,2,3

Notice that I'm letting the csv module work out where it needs to
put quote marks and where not (which is a lot of the reason for
its existence). I just pass it a list of strings, numbers, or
whatever and let it turn into a line.

I hope that this example helps you to understand the way you
would normally use the csv module. Feel free to come back to
ask more questions or to see how introduce it into your wider
codebase.

TJG


More information about the Tutor mailing list