I am trying to read in a CSV file and then returns all the data into a list. I first tried to read in the csv file using csv.reader by using the following code:
import csv
with open(fileName, 'r') as f:
next(f)
data = csv.reader(f)
dataList = list(data)
and I now have a list that looks like:
[['123', '234', '456', '567']
['345', '3456', '5678', '678']
['2345', '4567', '45678', '56789']
...]
I noticed that the numbers are stored as strings in the list, so I created a new list by newList = [int(i) for i in dataList] and I got this error message TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
so I tried the following code I saw on Youtube:
with open('fileName', 'r') as f:
next(f)
data = csv.reader(f)
data_lst = []
for line in reader:
data_lst.append([int(line)])
and I get this error message:
ValueError Traceback (most recent call last)
<ipython-input-123-9fbefdb892ab> in <module>
3 data = csv.reader(f)
4 data_lst = []
----> 5 for line in reader:
6 data_lst.append([int(line)])
ValueError: readline of closed file
Does anyone know how to convert the strings in the list into integers?
Many Thanks!
Sample csv file
number1 number2 number3 number4
0 123 456 567 5678
1 4567 3456 6789 2345
....
I need to read this csv file and that store the data in a list so that each row in the csv file is a list like [[123, 456, 567, 5678], [4567, 3456, 6789, 2345]...]
[[int(i) for i in l] for l in dataList]