The following code was working fine yesterday and now it only runs occasionally and gives the ‘name not defined error for kameradata’. I am a novice and dont know if its jupyter or my code. I have tried restarting the kernel but it still isnt running as it did yesterday.
JavaScript
x
14
14
1
import csv
2
3
def read_file(file_name):
4
data_list = []
5
with open(file_name,'r', encoding = 'UTF-8') as f:
6
csv_reader = csv.reader (f, delimiter = ';')
7
return data_list
8
9
for rad in csv_reader:
10
data_list.append(rad)
11
12
read_file('kameraData.csv')
13
print(kameradata[0:3])
14
The csv file looks like this: `
JavaScript
1
6
1
MätplatsID;Gällande Hastighet;Hastighet;Datum;Tid
2
14075010;40;55;2021-09-11;11:15:31
3
14075010;40;54;2021-09-11;08:09:17
4
14075010;40;53;2021-09-11;13:02:41
5
14075010;40;49;2021-09-11;13:02:55
6
I want to use the function to print the first 3 rows as follows:
JavaScript
1
4
1
['MätplatsID', 'Gällande Hastighet', 'Hastighet', 'Datum', 'Tid'],
2
['14075010', '40', '55', '2021-09-11', '11:15:31'], ['14075010', '40',
3
'54', '2021-09-11', '08:09:17']]
4
Advertisement
Answer
You’ve put return statement before loop and loop should be inside “with”. Try this code
JavaScript
1
8
1
def read_file(file_name):
2
data_list = []
3
with open(file_name,'r', encoding = 'UTF-8') as f:
4
csv_reader = csv.reader(f, delimiter = ';')
5
for rad in csv_reader:
6
data_list.append(rad)
7
return data_list
8