I open a file and read it with csv and I am trying to move the content to a function so that it can be reused in other programs in this format:
my-dic = []
with open('customer.csv','r') as input_file:
csv_reader = csv.reader(input_file,delimiter = ',')
for line_number, line in enumerate(csv_reader):
if line_number == 0: # skip the header
continue
def customer_file():
my_dic.append({
'First Name':line[1],
'Last name':line[2],
'Age(Years)':int(line[3]),
})
customer_file()
the csv files has 100 rows and ! am expecting the dictionary to be created for all the rows.On calling the function only the last row of the file is created . I read that this is late binding and that I have to force early binding by using default argument in the function. I passed line_number = 1, as parameter in the function so that it will start from line_number 1 of the csv file, this does not work too
How can I implement this so that when I call the function, the dictionary created will contain all the rows of the csv file not the last row only
If you wish to simplify your problem you can make use of list comprehension to obtain your required solution by using next(csv_reader)
in order to skip the first iteration of the loop.
import csv
with open('customer.csv','r') as input_file:
csv_reader = csv.reader(input_file,delimiter = ',')
next(csv_reader) # Skip header
my_dic = [{"First Name": line[0], "Last Name": line[1], "Age(Years)": int(line[2])} for line in csv_reader]
print(my_dic)
I will also provide a similar solution to what you provided as I cannot assume your knowledge with the Python language. The use of a function will not really be needed to append to your my_dic
dictionary, so I have eliminated that. You may need to adjust the indices where your data is situated as I am working of sample data I created.
import csv
my_dic = []
with open('customer.csv','r') as input_file:
csv_reader = csv.reader(input_file,delimiter = ',')
next(csv_reader) # Skip header
for n, line in enumerate(csv_reader):
print(line)
my_dic.append({
'First Name':line[0],
'Last name':line[1],
'Age(Years)':int(line[2]),
})
print(my_dic)
UPDATE as per comment
import csv
def dic_append(line):
my_dic.append({"First Name": line[0], "Last Name": line[1], "Age(Years)": int(line[2])})
my_dic = []
with open('customer.csv','r') as input_file:
csv_reader = csv.reader(input_file, delimiter = ',')
next(csv_reader) # Skip header
for line in csv_reader:
dic_append(line)
print(my_dic)