我试图用tell()
来显示我在文件描述符上的位置,但似乎总是指向错误的地方。文件描述符的位置
在下面的代码中,我用于读取data.txt
文件(代码下方),在所有运行过程中,POS打印到错误的位置(例如-10,9,...),最后打印的位置是93
,完全不同,它确实是。
然后接近结束时打印接下来的5个字节,它显示SPACE
后面的行。好吧,这是正确的,因为我已经阅读了线已经(其实我也试图获取pos
前readline()
,然后fd.seek
它。
但让我吃惊,如果我pos=fd.tell()
然后fd.seek(pos)
,它打印正是我想要的(但没想到)
如何被happenning
#!/usr/bin/env python
class space:
def read(self, filename):
with open(filename, "r") as fd:
hdr={}
while True:
line = fd.readline().split()
if line[0] == "SPACE":
break
key=line[0]
for value in line[1:]:
hdr.setdefault(key, []).append(value)
pos = fd.tell()
print pos,line
# Building the header
self.header = {
'x0' : int(hdr['XAXIS'][0]),
'dx' : int(hdr['XAXIS'][1]),
'xmax' : int(hdr['XAXIS'][2]),
'y0' : int(hdr['YAXIS'][0]),
'dy' : int(hdr['YAXIS'][1]),
'ymax' : int(hdr['YAXIS'][2]),
'nobjects' : int(hdr['NOBJECTS'][0]),
'objects' : hdr['OBJECT']
}
# Probably there is a best way to do this
self.x0 = self.header['x0']
self.y0 = self.header['y0']
self.dx = self.header['dx']
self.dy = self.header['dy']
self.xmax = self.header['xmax']
self.ymax = self.header['ymax']
self.nobjects = self.header['nobjects']
self.objects = self.header['objects']
# Storing the POSition of File Descriptor (just for safety)
pos = fd.tell()
print pos
# Why
print fd.read(5) # Gives me 1525
# While
fd.seek(pos)
print fd.read(5) # Gives me SPACE
# Didn't the fd position on first fd.read(5) was not pointing to correct
# place?
if __name__ == "__main__":
sp=space()
sp.read("data.txt")
运行上面返回代码:?
%./spc.py
-10 ['XAXIS', '1525', '2', '1767']
9 ['YAXIS', '1525', '2', '2011']
21 ['NOBJECTS', '5']
35 ['OBJECT', 'YAXIS']
49 ['OBJECT', 'XAXIS']
64 ['OBJECT', 'XCOORD']
79 ['OBJECT', 'YCOORD']
93 ['OBJECT', 'DEPTH']
114
1525
SPACE
这是data.txt
文件
XAXIS 1525 2 1767
YAXIS 1525 2 2011
NOBJECTS 5
OBJECT YAXIS
OBJECT XAXIS
OBJECT XCOORD
OBJECT YCOORD
OBJECT DEPTH
SPACE 29768 s1_0411
1525 1525 125000.01 125000.01 5933.09
1525 1527 125164.05 125000.01 5870.35
1525 1529 125328.09 125000.01 5836.18
1525 1531 125492.13 125000.01 5805.22
1525 1533 125656.17 125000.01 5735.52
1525 1535 125820.21 125000.01 5670.15
1525 1537 125984.26 125000.01 5617.8
1525 1539 126148.30 125000.01 5574
1525 1541 126312.34 125000.01 5538
1525 1543 126476.38 125000.01 5526
1525 1545 126640.42 125000.01 5553
1525 1547 126804.47 125000.01 5574
1525 1549 126968.51 125000.01 5588.17
1525 1551 127132.55 125000.01 5559.29
1525 1553 127296.59 125000.01 5454.46
1525 1555 127460.63 125000.01 5404.4
1525 1557 127624.68 125000.01 5356.67
1525 1559 127788.72 125000.01 5337
1525 1561 127952.76 125000.01 5323.71
1525 1563 128116.80 125000.01 5338.36
任何其他帮助,以提高代码,提示,技巧也欢迎。
如何做到以下几点:a)尽可能减少代码,b)当你明白它的作用时停止,c)加回步骤,直到行为再次变得陌生。 – NichtJens