使用Python将数组写入CSV文件(单列)

8
我想在Python中将一个数组的值写入.csv文件,但是当我在Excel中打开文件时,数据会显示在一行中。 我希望有一列,其中数组的每个成员都是一行。
这个数组testLabels的形式如下:
array(['deer', 'airplane', 'dog', ..., 'frog', 'cat', 'truck'], 
  dtype='<S10')

我使用的代码来写入csv文件是:

import csv
resultFile = open("/filepath",'wb')
wr = csv.writer(resultFile)
wr.writerows([testLabels])

任何帮助都将不胜感激。

这个问题早已有了关于Python方面的建议。然而,使用MS Excel中的函数会更容易:只需使用文本分列函数即可。 - MERose
5个回答

12

试一下这个:

wtr = csv.writer(open ('out.csv', 'w'), delimiter=',', lineterminator='\n')
for x in arr : wtr.writerow ([x])

5

您需要更改分隔符。CSV是逗号分隔值,但Excel理解逗号为“;”(是的很奇怪)。因此,您必须添加选项delimiter =“;”,例如:

csv.writer(myfile, delimiter=";")

Excel使用的分隔符是可配置的...但不是通过Excel进行配置的: http://www.howtogeek.com/howto/21456/export-or-save-excel-files-with-pipe-or-other-delimiters-instead-of-commas/ - deostroll

1
你需要将列表中的每个项目写入CSV文件的一行中,以使它们位于同一列中。
for label in testLabels:
    wr.writerows([label])

1

试试这个:

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)

0

试试这个:

    for i in range(len(testLabels)):
        result_file = open('filePath.csv', 'a')
        result_file.write("{}{}".format(testLabels[i], '\n'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接