def read_csv(file_name):
f=open(file_name).read()
lis=f.split("\n")
string_list=lis[1:len(lis)-1]
final_list=[]
for a in string_list:
string_fields=a.split(",")
int_field=[];
for value in string_fields:
int_field.append(int(value))
final_list.append(int_field)
return(final_list)
cdc_list=read_csv("US_births_1994-2003_CDC_NCHS.csv")
print(cdc_list[0:10])
This shows only the first element of cdc list.I am unable to find the error
It's because of your indentation. When you read your code you'll see, that you return
from your function after the first value
in string_list
Move your return 4 spaces to the left and it should work:
def read_csv(file_name):
f=open(file_name).read()
lis=f.split("\n")
string_list=lis[1:len(lis)-1]
final_list=[]
for a in string_list:
string_fields=a.split(",")
int_field=[];
for value in string_fields:
int_field.append(int(value))
final_list.append(int_field)
return(final_list)
cdc_list=read_csv("US_births_1994-2003_CDC_NCHS.csv")
print(cdc_list[0:10])
a shorter version:
def read_csv(file_name):
with open(file_name) as f:
#read lines
lines = [line.strip() for line in f.readlines()]
#remove header
lines = lines[1:]
# split lines and cast to integer
lines = [[int(val) for val in line.split(',')] for line in lines]
return(lines)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.