17

As the title says, I want to write a 2D array to a csv file with delimiter ',' using python. My array looks like this (ndarray):

a= [[1,2,3,4],[5,6,7,8]]

and I want the output to look like:

1,2,3,4
5,6,7,8

with open('./data/positive.csv','wb') as myfile:
  wr = csv.writer(myfile) #, quoting=csv.QUOTE_ALL)
  wr.writerow(a)

How do I accomplish this?

I already have tried the solution but it doesn't work since I misplaced an 's' in my 'row' and it makes my array write to a single row instead of multiple rows.

phouse512
  • 540
  • 3
  • 14
  • 23
JefferyLR
  • 351
  • 1
  • 4
  • 15
  • 2
    What have you tried? What is not working? Have you googled "python csv"? And read the documentation on the standard module showing up there? – Anthon Jun 22 '17 at 06:20
  • @AnoopToffy I have try the solution that you mention before but it write the 2D array in to one line. And i found that i misplace an 's' in my 'row', will edit the question. – JefferyLR Jun 22 '17 at 07:24

6 Answers6

25

Use csv module by import csv also take a note you might need either writerow() or writerows().

What's the difference you may ask?

writerow takes an iterable of cells to write:

writerow([1,2,2])
->
1,2,2

writerows takes an iterable of iterables of cells to write:

writerows([[1,2,3],
           [4,5,6],
           [6,7,8]])
->
1,2,3
4,5,6
6,7,8

Which can be ofcourse be given as a variable. Like

a = [[1,2,3],[4,5,6],[6,7,8]]
writerows(a)

Conclusion writerow takes 1-dimensional data (one row), and writerows takes 2-dimensional data (multiple rows).

Program for you:

import csv

a = [[1,2,3,4],[5,6,7,8]]

with open("new_file.csv","w+") as my_csv:
    csvWriter = csv.writer(my_csv,delimiter=',')
    csvWriter.writerows(a)

Note open() takes two arguments here the file to be written and the mode.

What is a mode you may ask?

It specifies how the file should be opened. In my case w+ means open file my_file.csv if it exists if it doesn't then fine create a new one and write.

There are several modes choose one. Note: w+ overwrites everytime you use it. That is old data in file will be overwritten so if you want to just append use a. Take a look at this for more details on modes.File modes

void
  • 2,254
  • 1
  • 16
  • 29
7

Assuming that a is a numpy array,

import numpy
a= [[1,2,3,4],[5,6,7,8]]
numpy.savetxt('output.csv',a,delimiter=",")
Rudresh Panchal
  • 910
  • 4
  • 15
3

Python's built in csv module does this easily:

import csv

a= [[1,2,3,4],[5,6,7,8]]

with open("output.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerows(a)
moritzg
  • 3,604
  • 3
  • 26
  • 55
  • yeah, this work well. I tried this before i post the question, and i found that i missplace an 's' in row make the entire array write in to one line. Thanks between. – JefferyLR Jun 22 '17 at 08:59
2

A simple way to achieve this is as follows.

a= [[1,2,3,4],[5,6,7,8]]
f = open('file.csv', 'w')
for item in a:
    for i in range(len(item)):
        if i == 0:
            f.write(str(item[i]))
        else:
            f.write(',' + str(item[i]))
    f.write('\n')
f.close()

Another alternative:

a= [[1,2,3,4],[5,6,7,8]]
f = open('file.csv', 'w')
for item in a:
    f.write(','.join([str(x) for x in item]) + '\n')
f.close()

Edit: Please note, use of csv module to write in csv files is always preferred. The solution I have suggested is more generic and can be useful to write things in any format in any type of file.

Wasi Ahmad
  • 27,225
  • 29
  • 85
  • 140
0

You can create a file object and print to a file, as below.

f=open('file.csv','w')
a= [[1,2,3,4],[5,6,7,8]]
for x in a:
  print(",".join([str(i) for i in x]), file=f)
f.close()
voidpro
  • 1,391
  • 10
  • 22
0

Python has a built in CSV module which can be used to read and write CSV's.

import csv
a= [[1,2,3,4],[5,6,7,8]]
with.open("myFile.csv", "w+") as myCsv:
     csvWriter = csv.writer(myCsv, delimiter=',')
     csvWriter.writerows(a)

You can read documentation on CSV module using This link.

EDIT: changed writeRow to writerows also removed wb and w+. Thanks @s_vishnu for pointing out the mistakes.

Shahbaaz
  • 325
  • 3
  • 9