Python: How to write a CSV file

CSV is one of the oldest and simplest format for spreadsheets.

If you've ever found yourself having to dump out some data in this format, Python makes it hella easy to do so.

headings = ['Category', 'Systemtype', 'SystemModel', 'ModelID', 'Type', 'Manufacturer', 'ProductName', 'OrigProductName', 'Processor', 'ProcessorSpeed', 'Monitor', 'Memory', 'OperatingSystem', 'HardDrive' ]

# Open up the CSV writer
file = open("something.csv", 'wb')
writer = csv.writer(file, delimiter = ',', quotechar = '"')

row = []
for field in headings:
row.append(p.get(field, '').strip().encode("utf-8"))


As you can see, the csv module makes life really easy!

One thing to keep in mind is the encode("utf-8") bit is important, as the CSV module doesn't support unicode by default.


Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog