Home > Mobile >  Extract part of a text file with python
Extract part of a text file with python

Time:08-12

I have a text file which is of the form :

Initialization
Background
Starting_Measurement1
1
2
3
...
100
End_Measurement1
Starting_Measurement2
1
2
3
...
75
End_Measurement2

I would like to store the values between Starting_Measurement1 and End_Measurement1 and then between Starting_Measurement2 and End_Measurement2, but the number of value is variable

Is there a clean way to do this in python?

CodePudding user response:

b = textInput.split('\n')

start1 = b.index('Starting_Measurement1')
end1 = b.index('End_Measurement1')

measureList1 = list(b[start1:end1])

And repeat for the other Measurements

CodePudding user response:

It's perhaps not the most elegant solution, but it should do what you want:

Contents of text file named data.txt:

Initialization
Background
Starting_Measurement1
1
2
3
4
5
100
End_Measurement1
Starting_Measurement2
1
2
3
75
End_Measurement2

Code that reads the file and extracts the numbers into a list of lists:

with open('data.txt') as f:
    s = f.read()

all_measurements = []
reading = False
for line in s.splitlines():
    if line.startswith('Starting_Measurement'):
        current_measurements = []
        reading = True
    elif line.startswith('End_Measurement'):
        all_measurements.append(current_measurements)
        reading = False
    elif reading:
        value = int(line)
        current_measurements.append(value)

print(all_measurements)

Resulting in:

[[1, 2, 3, 4, 5, 100], [1, 2, 3, 75]]

CodePudding user response:

filename = "measurements.txt"

measurements = []
measurement_lines = []
line_in_measurement = False
with open(filename, "rt") as file:
    for line in file:
        line = line.strip("\n")
        if "Starting_Measurement" in line:
            measurement_lines = []
            line_in_measurement = True
        elif "End_Measurement" in line:
            measurements.append(measurement_lines)
            line_in_measurement = False
        elif line_in_measurement:
            measurement_lines.append(line)

for measure_number, measure in enumerate(measurements):
    print(f"measurement {measure_number}")
    print(measure)
  • Related