Created
September 22, 2012 18:43
-
-
Save dettmering/3767366 to your computer and use it in GitHub Desktop.
Python: Read CSV file into array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
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!
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
@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