0

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'

Ébe Isaac
  • 11,563
  • 17
  • 64
  • 97
  • 1
    http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface –  Nov 15 '16 at 15:53
  • yes. I went through it. But I am getting this error, when I tried that **c.write(bytes(df, 'UTF-8')) AttributeError: '_csv.writer' object has no attribute 'write'** –  Nov 15 '16 at 15:55
  • Add what you tried and the error you get to your question so people can help you better. –  Nov 15 '16 at 15:56
  • http://stackoverflow.com/questions/20639531/csv-writer-object-has-no-attribute-write –  Nov 15 '16 at 15:57
  • Ya I have updated the code and error along with the question. –  Nov 15 '16 at 16:00
  • Googling the error you get will usually help. –  Nov 15 '16 at 16:02

1 Answers1

0

You want to use to_csv

df.to_csv(path + filename)
mauve
  • 2,707
  • 1
  • 20
  • 34