the_list = [['a','b','c'],['b','c','d'],['c','d','e']]
output = []
for k in the_list:
output.append(str(k)[1:-1].replace(',',"\t").replace("'",'').replace(' ',''))
print output
#['a\tb\tc', 'b\tc\td', 'c\td\te']
#for line in output:
#out_file.write(line + '\n')
I'm trying to get the list into tab-delmited format so i can write to an .xls file but the only way i could figure out how to do it seemed pretty monotonous . I was wondering if anyone knew a quicker, more efficient, and more 'pythonic' way of writing a list to an .xls
Use the built-in
csv
library. http://docs.python.org/2/library/csv.htmlAssuming
out_file
is already opened, as in the commented out parts of your example:To be a bit pedantic, you're trying to write a tab-delimited file rather than actual Excel. Excel can handle tab-delimited files just fine, but if you need true Excel
xlwt
is the usual library. Using it you'd have something like this:If you have to write to XLS, I would use the answers given here:
Python - Write to Excel Spreadsheet
You can accomplish the formatting you're looking for with a list comprehension
See python's documentation on join.
While using tab separated variables or csv will often work, expect failure if you need UTF-8. You will not see the characters you expect once you get out of the ASCII range.
I have not tried the real Excel products mentioned in saxman01's references, but they might be more suitable if the target is really Excel. Will they handle other character sets? Just something to think about if you need to go international (or even domestic to non-English speaking audience).
Then you could be asking yourself, what would Google Docs do?