简体   繁体   中英

read from file line by line , multiple match in file possible

I am reading form a file and trying to produce the following:

  1. Search the file to find the "temperature", where "temperature" can occur several times in file
  2. Organize the data: produce 4 lists:

    • 1st list: list_planes_r (name of the planes): [plane_r_01, plane_r_02, plane_r_03, plane_r_04]
    • 2nd list: temp_plane_r (temperature values): [54, 50, 52, 10]
    • 3rd list: list_planes_f: [plane_f_01, plane_f_02, plane_f_03, plane_f_04]
    • 4th list: temp_plane_f: [1254, 1354, 1454, 1554]

I am always running in the problem of having to split a list, which of course I am not allowed to do.

I did as below:

with open ('test_reading_file.txt', 'r') as f:
   lines = f.readlines()
list_lines = []
for index, line in enumerate(lines):
 if   ('  temperature') in line:
        list_lines.append(lines[index+1: index+5]

My toy file 'test_reading_file.txt'

  temperature
-------
 plane_r_01          54
 plane_r_02          50
 plane_r_03          52
 plane_r_04          10


  co
-------
 plane_r_01          54
 plane_r_02          54
 plane_r_03          54
 plane_r_04          54

  temperature
-------
 plane_f_01          1254
 plane_f_02          1354
 plane_f_03          1454
 plane_f_04          1454

Update: pictures current_output

Here is the shorter version:

list_planes = []
list_temperatures = []
[list_planes.append([sub.split()[0] for sub in content]) for content in list_lines]
[list_temperatures.append([sub.split()[1] for sub in content]) for content in list_lines]

list_planes_r, list_planes_f = list_planes
temp_plane_r, temp_plane_f = list_temperatures

I have not completely clear what do you want, but my best guess is that you want two list (say planes and temperatures ) so that you can do

for plane, temperature in zip(planes, temperatures):
    ...

The code that I produced according to this guess is

planes, temperatures = [], []
with open('...') as f:

    for line in f:
        if line.strip() == 'temperatures':
            next(f)  # skip a line
            for n in range(4):
                p, t = next(f).strip().split()
                planes.append(p)
                temperatures.append(t)

I have checked the results.

The code works because a file object (here f ) is an iterator and we can advance inside the iterator, consuming the iterator, using the next builtin.

The use case in which you scan a file and read some lines when you find a keyword is a canonical example of using next ; not using next means using a flag and raising/clearing it as you enter/exit from the interesting zone...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM