I have a strange error in the following code:
s = MyClass()
f = open(filename, 'r')
nbline = f.readline()
for line in iter(f):
linesplit = line.split()
s.add(linesplit)
f.close()
print(len(s.l))
print(nbline)
the two print don't give me the same result. Why?
the class definition is:
class MyClass:
l = []
def add(self, v):
self.l.append(v)
and the file format is:
161
3277 4704 52456568 0 1340 380 425
3277 4704 52456578 1 1330 380 422
3118 4719 52456588 1 1340 390 415
3109 4732 52456598 1 1340 400 420
3182 4743 52456608 1 1350 410 427
3309 4789 52456618 1 1360 420 446
...
for this file the print are: 51020 161
and the file contain 162 line (the number of line + the line)
If I call the function one it's ok, the error appear when I call the function twice or more (it's look like previous file are read!!! :/)
First, thanks for the edit.
Here is a better looking and more pythonic code:
s = MyClass()
with open(filename, 'r') as f:
nbline = f.readline()
for line in f:
linesplit = line.split()
s.add(linesplit)
Then make sure you are setting self.l = []
in your MyClass