this is my list
list=['a','b','c']
when using this code
with open('commentafterlink.csv', 'w') as f:
f.write("%s\n" % list)
it stores each token of list in a one cell but i need to store whole list in one cell.where is the problem?
Can you try the following:
import xlwt
from xlwt import Workbook
# Workbook is created
wb = Workbook()
# add_sheet is used to create sheet.
sheet1 = wb.add_sheet('Sheet 1')
# sheet1.write(1, 0, ' '.join(list))
# if you want the output to be ['a','b','c']
sheet1.write(1, 0, str(list))
wb.save('xlwt example.xls')
Output:
1) You are not writing an Excel file, but a CSV file (that Excel knows how to import).
2) You are writing to the CSV file as if it was a text file, without respecting the semantics of CSV. CSV means "comma-separated values". If it contains the text ['a','b','c'], it will be interpreted as three columns: ['a' and 'b' and 'c']. You would need to quote the value in order to do it right; the default quote in CSV is a double quote. So if you write "['a','b','c']", this would be imported into Excel as one cell. However,
3) You are writing CSV file by hand, which means it is very easy to get the format wrong (e.g. forget to escape something that needs to be escaped). In general, whenever you are writing a file with an established format, it is worth checking if the format has a library that knows how to handle it. Python natively knows how to write CSV files using the csv module, and it knows how to write Excel files using packages you can install using pip, such as xlwt.
Here is how you write a CSV file correctly:
my_list = ['a', 'b', 'c']
import csv
with open('commentafterlink.csv', 'w') as w:
writer = csv.writer(w)
writer.writerow([str(my_list)])
Note: It is a Bad Thing to overwrite Python's built-in variables, such as list.
(I see another answerer has already provided you the Excel-specific solution using xlwt.)
Using join():
lst=['a','b','c']
with open('commentafterlink.csv', 'w') as f:
f.write("%s\n" % "".join(lst))
OUTPUT:
EDIT:
Using repr():
import xlsxwriter
lst=['a','b','c'] # avoid using list keyword
workbook = xlsxwriter.Workbook('commentafterlink.xlsx') # create/read the file
worksheet = workbook.add_worksheet() # adding a worksheet
worksheet.write('A1', repr(lst)) # write repr(lst) to cell A1
workbook.close() # close the file
OUTPUT:
join()