I am working on a code where I need to convert a dataset of sentences in a txt file to an csv file. here is my code which works fine, converting the input txt file to the format of a csv file.
However, i am not able to make an output csv file. I am new to python programming and so I don't know my way around it as of yet.
Here's my code:
def txtTOcsv():
output_csv = []
with open("dataset.txt", "r") as myfile:
lines = myfile.readlines()
for line in lines:
row = line.split()
for i in row[1:]:
tokens = (row[0],i)
print tokens
output_csv.append(tokens)
with open(output_csv,'w') as out_file:
csv.writer(out_file)
It works fine till
print tokens
and prints all the columns with commas in between just as I want. but when it goes to the line where the output is to be saved in a csv file. it gives this error:
with open(output_csv,'w') as out_file:
TypeError: coercing to Unicode: need string or buffer, list found
Any help would be greatly appreciated. thanks.
output_csv.append(tokens)line works for you? post the value oftokensvariable. - Avinash Raj