Python - 将数据帧写入csv文件

时间:2016-11-15 15:51:48

标签: python pandas dataframe export-to-csv

我希望使用python将我的数据框写入csv文件。我正在使用pandas从我的输入文本文件构建数据框。这是我的代码,

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'))

当我运行它时,它在最后一行给出了一个错误 -      c.writerow(字节(df,' UTF-8')) TypeError:' str'不支持缓冲区接口。请帮助我。我希望我的数据框输出在我的csv文件中。提前谢谢。

这是更新后的代码,

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'))

我得到的错误就是这个, c.write(bytes(df,' UTF-8')) AttributeError:' _csv.writer'对象没有属性'写'

1 个答案:

答案 0 :(得分:0)

You want to use to_csv

df.to_csv(path + filename)