Skip to content
Advertisement

Code not working in Jupyter Notebook, csv file, name error

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.

import csv

def read_file(file_name):
    data_list = []
    with open(file_name,'r', encoding = 'UTF-8') as f:
        csv_reader = csv.reader (f, delimiter = ';')
        return data_list

    for rad in csv_reader:
        data_list.append(rad)

read_file('kameraData.csv')
print(kameradata[0:3])

The csv file looks like this: `

MätplatsID;Gällande Hastighet;Hastighet;Datum;Tid
14075010;40;55;2021-09-11;11:15:31
14075010;40;54;2021-09-11;08:09:17
14075010;40;53;2021-09-11;13:02:41
14075010;40;49;2021-09-11;13:02:55

I want to use the function to print the first 3 rows as follows:

['MätplatsID', 'Gällande Hastighet', 'Hastighet', 'Datum', 'Tid'],  
   ['14075010', '40', '55', '2021-09-11', '11:15:31'], ['14075010', '40',  
    '54', '2021-09-11', '08:09:17']] 

Advertisement

Answer

You’ve put return statement before loop and loop should be inside “with”. Try this code

def read_file(file_name):
    data_list = []
    with open(file_name,'r', encoding = 'UTF-8') as f:
        csv_reader = csv.reader(f, delimiter = ';')
        for rad in csv_reader:
            data_list.append(rad)
        return data_list
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement