Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

kimenye commented Feb 16, 2018

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

@TheTrueDM

This comment has been minimized.

Copy link

TheTrueDM commented Feb 20, 2018

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

@ademidun

This comment has been minimized.

Copy link

ademidun commented Apr 27, 2018

@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

This comment has been minimized.

Copy link

PratyushTripathy commented Jan 2, 2019

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.