我有一个包含多行格式的文件,语法如下:
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
数据全部为ASCII格式。
一行的例子是:
011084 31.0581 -87.0547 26.0 AL BREWTON 3 SSE ------ ------ ------ +6
我目前的想法是,我想一次读取一行文件,以某种方式将每一行分解成字典,这样我就可以引用组件。是否有一些模块可以用 Python 或其他一些简洁的方式执行此操作?
谢谢!
最佳答案
编辑:您仍然可以使用结构模块:
参见 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)
关于Python 读取格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7111690/