2016-11-15 212 views
0

我正在尋找使用python將我的數據框寫入csv文件。我利用大熊貓建立從我輸入的文本文件。這個數據幀是我的代碼,Python - 將數據框寫入csv文件

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

,當我運行這一點,讓我在最後一行在這裏的錯誤 - ℃。 Writer(字節(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(字節(DF, 'UTF-8')) AttributeError的: '_csv.writer'對象沒有屬性 '寫'

+1

http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-th e-buffer-interface –

+0

是的。我經歷了它。但我得到這個錯誤,當我嘗試** c.write(bytes(df,'UTF-8')) AttributeError:'_csv.writer'對象沒有屬性'寫'** –

+0

添加你試過的以及您遇到的問題,以便人們可以更好地幫助您。 –

回答