2016-11-15 25 views
0

Pythonを使用してデータフレームをcsvファイルに書き込むことを検討しています。私は私の入力テキストからのデータフレームを構築するためにパンダを利用することfile.Thisは、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')) 

私のコードであり、私はこれを実行すると、それは私にここに最終ラインでオーバーエラー与えています - Cを。 writerow(bytes(df、 'UTF-8')) TypeError: 'str'はバッファインターフェイスをサポートしていません。親切に私にこれを手伝ってください。データフレームの出力を自分のCSVファイルの中に入れたい。前もって感謝します。 '_csv.writer':

この更新されたコード、

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

と私は取得していますエラーが( 'UTF-8')、バイト(DF) はAttributeErrorこの、c.writeですオブジェクトには、属性 '書き込み'

+1

http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-thを持っていませんe-buffer-interface –

+0

はい。私はそれを通過した。しかし、このエラーが発生しました。** c.write(バイト(df、 'UTF-8')) AttributeError: '_csv.writer'オブジェクトに属性 'write'がありません** –

+0

試したものを追加人々があなたをより良く助けることができるように、あなたはあなたの質問に間違いを感じます。 –

答えて

関連する問題