简体   繁体   English

Python-将数据帧写入csv文件

[英]Python - write data frame into a csv file

I am looking to write my data frame into csv file using python. 我正在使用python将数据帧写入csv文件。 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 . 当我运行它时,它在最后一行给我一个错误-c.writerow(bytes(df,'UTF-8'))TypeError:'str'不支持缓冲区接口 Kindly help me with this. 请帮助我。 I want my output of the dataframe to be inside my csv file. 我希望数据框的输出位于cs​​v文件中。 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' 和我得到的错误是这样的, c.write(bytes(df,'UTF-8'))AttributeError:'_csv.writer'对象没有属性'write'

您要使用to_csv

df.to_csv(path + filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM