Reputation: 283
I have a question about this program:
%%file data.csv
x1,x2,y
0.4946,5.7661,0
4.7206,5.7661,1
1.2888,5.3433,0
4.2898,5.3433,1
1.4293,4.5592,0
4.2286,4.5592,1
1.1921,5.8563,0
3.1454,5.8563,1
f = open('data.csv')
data = []
f.readline()
for line in f:
(x1,x2,y) = line.split(',')
x1 = float(x1)
x2 = float(x2)
y = int(y)
data.append((x1,x2,y))
What is the purpose of readline here? I have seen different examples but here seems that it delete the first line.
Upvotes: 3
Views: 81
Reputation: 1949
Using readline()
method before reading lines of file in loop
is equals to:
for line in f.readlines()[1:]:
...
for example that may be used to skip table header.
In your file, when you will convert x1
variable to float type it raise ValueError
because in first iteration x1
contain not digit sting type value "x1"
. And to avoid that error you use readline()
to swich iterator to second line wich contain pure digits.
Upvotes: 1
Reputation: 136
Python is reading the data serially, so if a line gets read once, python jumps to the next one. The r.readline() reads the first line, so in the loop it doesn't get read.
Upvotes: 5
Reputation: 24721
That's precisely the point: to delete the first line. If you notice, the file has the names of the columns as its first line (x1,x2,y
), and the program wants to ignore that line.
Upvotes: 3