21

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.

2
  • 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, 2017 at 6: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, 2017 at 7:24

6 Answers 6

32

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

1
  • 3
    Thanks very much for mentioning 'row' and 'rows'. It solved my problem .
    – JefferyLR
    Jun 22, 2017 at 7:00
10

Assuming that a is a numpy array,

import numpy
a= [[1,2,3,4],[5,6,7,8]]
numpy.savetxt('output.csv',a,delimiter=",")
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)
1
  • 1
    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, 2017 at 8:59
3

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.

3
  • 3
    That's actually way too overkill, given that the csv module does all of this more or less automatically.
    – moritzg
    Jun 22, 2017 at 6:21
  • @moritzg I agree, I was just suggesting a simple way.
    – Wasi Ahmad
    Jun 22, 2017 at 6:23
  • it only uses basic file operations, no additional module usage is required.
    – Wasi Ahmad
    Jun 22, 2017 at 6:49
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()
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.

1
  • Please check your code, it doesn't work in its current form. Jun 22, 2017 at 6:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.