2017-11-14 31 views
1

私はzip構文を使って2つのリストを結合しました。 CSV形式で保存すると、データ全体が1つのセルに収まるようになりました。私が望むのは、ZIPファイルの各要素は各行にとどまるべきです。pythonファイルでのcsv形式の操作

これは私のコードです:

list_of_first_column=["banana","cat","brown"] 
list_of_second_column=["fruit","animal","color"] 

graph_zip_file=zip(list_of_first_column,list_of_second_column) 
with open('graph.csv', 'w') as csv_file: 
    writer = csv.writer(csv_file) 
    writer.writerow(graph_zip_file) 

私はcsv形式で欲しいもの:

banana,fruit 
cat,animal 
brown,color 
+0

'writer.writerow(graph_zip_file)'を 'writer.writerows(graph_zip_file)'に置き換えてください。 – Abdou

答えて

2

あなたはcsvモジュールを使用していると仮定して、これを行う方法を2つ持っています。あなたはwriter.writerowsを使用することができ、次のいずれか

list_of_first_column = ["banana", "cat", "brown"] 
list_of_second_column = ["fruit", "animal", "color"] 

graph_zip_file = zip(list_of_first_column, list_of_second_column) 
with open('graph.csv', 'w') as csv_file: 
    writer = csv.writer(csv_file) 
    writer.writerows(graph_zip_file) 

それとも、あなたはwriter.writerowfor-loopを使用することができます。

list_of_first_column = ["banana", "cat", "brown"] 
list_of_second_column = ["fruit", "animal", "color"] 

graph_zip_file = zip(list_of_first_column, list_of_second_column) 
with open('graph.csv', 'w') as csv_file: 
    writer = csv.writer(csv_file) 
    for row in graph_zip_file 
     writer.writerow(row) 

彼らの両方が、ご希望の出力として示さたもので、同じことを、返す必要があります。

私はこれが有用であることを望みます。

+0

私はwritrowosをwriterに変更しました。どうもありがとうございます –

関連する問題