Skip to content

Instantly share code, notes, and snippets.

@dettmering
Created September 22, 2012 18:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dettmering/3767366 to your computer and use it in GitHub Desktop.
Save dettmering/3767366 to your computer and use it in GitHub Desktop.
Python: Read CSV file into array
def readcsv(filename):
ifile = open(filename, "rU")
reader = csv.reader(ifile, delimiter=";")
rownum = 0
a = []
for row in reader:
a.append (row)
rownum += 1
ifile.close()
return a
@kimenye
Copy link

kimenye commented Feb 16, 2018

Add the line import csv at the beginning to make this work.

@TheTrueDM
Copy link

What does the "U" do in the "rU", because I know r is read.

@ademidun
Copy link

@TheTrueDM its universal newlines mode. I think it allows each new line in a csv to be a separate item in the reader/ifile array. So basically it will recognize the following character sequences as new lines.:
Unix end-of-line convention '\n', the Windows convention '\r\n', and the old Macintosh convention '\r'

Note: Its been deprecated from python 3.4+, will be removed in python 4 (There's a python 4??)
See:
https://docs.python.org/3/library/functions.html (use find 'U' on your browser to see the relevant section
https://docs.python.org/3/glossary.html#term-universal-newlines

@PratyushTripathy
Copy link

I think a better way would be to use Pandas using the following function:
def readcsv(filename):
data = pd.read_csv(filename) #Please add four spaces here before this line
return(np.array(data)) #Please add four spaces here before this line

yourArray = readcsv(yourFilename)
Good Luck!

@thejose5
Copy link

This reads each row as a string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment