Menu

[r8866]: / trunk / course / examples / parse_file.py  Maximize  Restore  History

Download this file

24 lines (18 with data), 762 Bytes

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# read in the cvs file family.dat
# open the file for reading
fh = file('../data/family.csv', 'r')
# slurp the header, splitting on the comma
headers = fh.readline().split(',')
# now loop over the remaining lines in the file and parse them
for line in fh:
# remove any leading or trailing white space
line = line.strip()
# split the line on the comma into separate variables
first, last, age, weight, height, dob = line.split(',')
# convert some of these strings to floats
age, weight, height = [float(val) for val in (age, weight, height)]
print first, last, age, weight, height, dob
results = []
for line in fh:
# process the line as above to get the variables
results.append( (first, last, age, weight, height, dob) )
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.