将数组写入 csv python(一列)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21465447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing array to csv python (one column)
提问by user3240210
I'm trying to write the values of an array to a .csv file in python. But when I open the file in excel, the data is shown in one row. I want to have one column where each member of the array is a row.
我正在尝试将数组的值写入 python 中的 .csv 文件。但是当我在excel中打开文件时,数据显示在一行中。我想要一列,其中数组的每个成员都是一行。
The array "testLabels" is of the form:
数组“testLabels”的形式如下:
array(['deer', 'airplane', 'dog', ..., 'frog', 'cat', 'truck'],
dtype='<S10')
And the code I use to write to the csv is:
我用来写入 csv 的代码是:
import csv
resultFile = open("/filepath",'wb')
wr = csv.writer(resultFile)
wr.writerows([testLabels])
Any help would be greatly appreciated.
任何帮助将不胜感激。
回答by MatthieuBizien
You should change the delimiter. CSV is Comma Separated Value, but Excel understands that a comma is ";" (yeah weird). So you have to add the option delimiter=";", like
您应该更改分隔符。CSV 是逗号分隔值,但 Excel 理解逗号是“;” (是的,很奇怪)。所以你必须添加选项 delimiter=";",比如
csv.writer(myfile, delimiter=";")
回答by Carlos Hanson
You need to write each item of list to a row in the CSV file to get them into one column.
您需要将列表的每一项写入 CSV 文件中的一行,以将它们放入一列。
for label in testLabels:
wr.writerows([label])
回答by deostroll
Try this:
尝试这个:
wtr = csv.writer(open ('out.csv', 'w'), delimiter=',', lineterminator='\n')
for x in arr : wtr.writerow ([x])
回答by Pratyush Tripathy
Try this:
尝试这个:
import csv
import numpy as np
yourArray = ['deer', 'airplane', 'dog', ..., 'frog', 'cat', 'truck']
yourArray = np.array(yourArray)
with open('outputFile.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for row in range(0,yourArray.shape[0]):
myList = []
myList.append(yourArray[row])
writer.writerow(myList)
回答by Altan
Try this:
尝试这个:
for i in range(len(testLabels)):
result_file = open('filePath.csv', 'a')
result_file.write("{}{}".format(testLabels[i], '\n'))

