【发布时间】:2017-03-29 14:13:02
【问题描述】:
我希望使用 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(bytes(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' 对象没有属性 'write'
【问题讨论】:
-
是的。我经历了它。但是当我尝试 c.write(bytes(df, 'UTF-8')) AttributeError: '_csv.writer' object has no attribute 'write'时,我遇到了这个错误>
-
将您尝试过的内容和遇到的错误添加到您的问题中,以便人们可以更好地帮助您。
-
是的,我已经更新了代码和错误以及问题。
标签: python pandas dataframe export-to-csv