8

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.

The array "testLabels" is of the form:

array(['deer', 'airplane', 'dog', ..., 'frog', 'cat', 'truck'], 
  dtype='<S10')

And the code I use to write to the csv is:

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

Any help would be greatly appreciated.

user3240210
  • 143
  • 1
  • 2
  • 6
  • The question has long been answered with suggestions on python side. However, using a function in MS Excel would have been easier: Simply use the [text-to-columns function](http://www.excel-easy.com/examples/text-to-columns.html). – MERose Feb 17 '15 at 13:41

5 Answers5

12

Try this:

wtr = csv.writer(open ('out.csv', 'w'), delimiter=',', lineterminator='\n')
for x in arr : wtr.writerow ([x])
deostroll
  • 11,661
  • 21
  • 90
  • 161
5

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.writer(myfile, delimiter=";")
MatthieuBizien
  • 1,647
  • 1
  • 10
  • 19
  • The delimiter excel uses is configurable...but its not through excel though: http://www.howtogeek.com/howto/21456/export-or-save-excel-files-with-pipe-or-other-delimiters-instead-of-commas/ – deostroll Jan 30 '14 at 19:34
1

You need to write each item of list to a row in the CSV file to get them into one column.

for label in testLabels:
    wr.writerows([label])
1

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

Try this:

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