我有一个文件,其中包含许多使用以下语法格式化的行:
FIELD POSITION DATA TYPE
------------------------------
COOP ID 1-6 Character
LATITUDE 8-15 Real
LONGITUDE 17-25 Real
ELEVATION 27-32 Real
STATE 34-35 Character
NAME 37-66 Character
COMPONENT1 68-73 Character
COMPONENT2 75-80 Character
COMPONENT3 82-87 Character
UTC OFFSET 89-90 Integer
Run Code Online (Sandbox Code Playgroud)
数据全部是ASCII格式的.
一行的例子是:
011084 31.0581 -87.0547 26.0 AL BREWTON 3 SSE ------ ------ ------ +6
Run Code Online (Sandbox Code Playgroud)
我目前的想法是,我想一次读取一行中的文件,并以某种方式将每行分解为字典,以便我可以参考组件.是否有一些模块在Python中执行此操作,或其他一些干净的方式?
谢谢!
Kim*_*ais 15
编辑:您仍然可以使用struct模块:
请参阅struct module文档.在我看来,你想要使用struct.unpack()
你想要的可能是这样的:
import struct
with open("filename.txt", "r") as f:
for line in f:
(coop_id, lat, lon, elev, state, name, c1, c2, c3, utc_offset
) = struct.unpack("6sx8sx9sx6sx2sx30sx6sx6sx6sx2s", line.strip())
(lat, lon, elev) = map(float, (lat, lon, elev))
utc_offset = int(utc_offset)
Run Code Online (Sandbox Code Playgroud)