I am looking to write my data frame into csv file using python. I am making use of pandas to build the data frame from my input text file.This is my Code,
import pandas
import csv
txt_file = r"sida.txt"
txt = open(txt_file, "r")
txt_string = txt.read()
txt_lines = txt_string.split("\n")
txt_dict = {}
c = csv.writer(open("MYFILE.csv", "wb"))
for txt_line in txt_lines:
k,v = txt_line.split(":")
k = k.strip()
v = v.strip()
if k in txt_dict:
list = txt_dict.get(k)
else:
list = []
list.append(v)
txt_dict[k]=list
df=(pandas.DataFrame.from_dict(txt_dict, orient="index"))
print(df)
c.writerow(bytes(df, 'UTF-8'))
and when I run this it gives me an error over here in the final line - c.writerow(bytes(df, 'UTF-8')) TypeError: 'str' does not support the buffer interface. Kindly help me with this. I want my output of the dataframe to be inside my csv file. Thanks in advance.
This is updated code,
for txt_line in txt_lines:
k,v = txt_line.split(":")
k = k.strip()
v = v.strip()
if k in txt_dict:
list = txt_dict.get(k)
else:
list = []
list.append(v)
txt_dict[k]=list
df=(pandas.DataFrame.from_dict(txt_dict, orient="index"))
print(df)
c.write(bytes(df, 'UTF-8'))
and the error that I am getting is this, c.write(bytes(df, 'UTF-8')) AttributeError: '_csv.writer' object has no attribute 'write'