Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python read .txt-files header

Tags:

python

file

numpy

I need to read some information from a txt file header which looks like this:

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

Height  Value   Comment
60  NaN 
...

I have a python program program currently doing this:

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

However I would like to read out some of the values from the header. Is there a way to do this? I am mostly interested to get the value of "Total Height". On my search I only seem to find answers concerning .csv files.

like image 288
brium-brium Avatar asked Sep 06 '25 23:09

brium-brium


2 Answers

I would use open rather than 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:]

Then you can parse the value of height_line, to get the Total Height. And all your data from the file will be in the variable data.

like image 176
eric.christensen Avatar answered Sep 09 '25 13:09

eric.christensen


This should work!

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

If you know that the field names and values are separated by a tab character instead of spaces, you could instead use line.split('\t') to break each line into the field name and field value, and then just check if field_name is the field you care about, and if so, use the value, instead of using startswith and then slicing the resulting string to get the end of it.

like image 24
Christopher Shroba Avatar answered Sep 09 '25 14:09

Christopher Shroba