tell()
を使用してファイル記述子の位置を表示しようとしていますが、常に間違った場所を指しているようです。ファイル記述子の位置
私がdata.txt
ファイル(コードの下)を読み取るために使用している以下のコードでは、POSが間違った位置(たとえば-10、9、...)に印刷されている間に、最後に印刷される位置は93
、それは本当に異なっています。
最後に、次の5バイトが印刷され、SPACE
の後の行が表示されます。私はすでにラインを読んだことがあるので、[OK]を、それが正しいか(実際に私も。そしてfd.seek
それをpos
前readline()
をフェッチする
を試みたが、私の驚きに私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