Python read.txt文件头

2024-04-27 04:09:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从txt文件头中读取一些信息,如下所示:

Date    20160122
SP Number   8
Gauge   250N internal
Total Height    61
SP Modell   SP2
Corner Distance 150 

Height  Value   Comment
60  NaN 
...

我有一个python程序正在执行以下操作:

depth, N = npy.loadtxt(filename, skiprows=8, unpack=True, usecols = usecols)

不过,我想从标题中读出一些值。有办法吗?我最感兴趣的是得到“总高度”的值。在我的搜索中,我似乎只找到有关.csv文件的答案。


Tags: 文件txt信息numberdatespdistancetotal
3条回答

这应该管用!

field = "Total Height"

# Get first 6 lines
with open(filename) as file:
    lines = [next(file) for x in range(6)]

value = None
for line in lines:
    if line.startswith(field):
        # Get the part of the string after the field name
        end_of_string = line[len(field):]

        # Convert it to an int:
        value = int(end_of_string.strip())

print(value) #Should print 61

如果知道字段名和值由制表符而不是空格分隔,则可以使用line.split('\t')将每一行拆分为字段名和字段值,然后检查字段名是否是您所关心的字段,如果是,则使用该值,而不是使用startswith,然后对结果字符串进行切片以得到其结尾。

这样就可以了,但有一点要注意:

import numpy as npy

usecols = (0, 1)

header = {}
with open(filename, 'rt') as f:
    for header_lines, line in enumerate(f):
        line = line.strip()
        if not line: break # assume that a blank line means "header stops here"
        key, value = line.split(' ', 1)
        header[key] = value


depth, N = npy.loadtxt(filename, skiprows=header_lines + 2, unpack=True, usecols=usecols)

问题是头格式对于什么是键和什么是值有歧义。有些键似乎是多个空格分隔的词,有些值也是,但是(数量不确定)空白也显然是分隔键和值的唯一规则。在大多数情况下,键和值之间有3个空格,但是Corner Distance后面只有1个空格,因此键结束和值开始的位置不明确(除了人脑自己复杂的上下文解析器)。

可能问题是对真正应该是选项卡的渲染(在这个页面上,或者在复制粘贴到SO中)不好。如果是的话

        key, value = line.split('\t', 1)

会解决问题的。但如果没有,则需要先解决文件格式中的歧义,然后才能编写最终的解决方案。

我会用open而不是npy.loadtxt

with open(filename, 'r') as the_file:
    all_data = [line.strip() for line in the_file.readlines()]
    height_line = all_data[3]
    data = all_data[8:]

然后可以解析height_line的值,以获得总高度。文件中的所有数据都在变量data中。

相关问题 更多 >