简体   繁体   中英

Concatenate records from a file in Python

Since I'm a newbie in Python programing I need to ask here:-) I have a text file with records like this

UCB: Some information
   FCB: More information
   FCB: More information
   FCB: More information
      WCB: Final information
   FCB: More information
   FCB: More information
      WCB: Final information
      WCB: Final information
      WCB: Final information
UCB: Some information
   FCB: More information
   FCB: More information
      WCB: Final information
   FCB: More information

The number of FCB and WCB records is different from time to time. The only thing I know is that

  1. The UCB record is always followed by at least one FCB-record.
  2. The FCB record(s) belongs to the last UCB record read
  3. The WCB record(s) belongs to the last FCB record that was read
  4. The FCB record can have zero up to hundreth of WCB records
  5. The number of UCB records is unknown

I need to read the file and concatenate the UCB record with a FCB record if and only if the FCB is followed by one (or more) WCB record(s). In that case the output record should be UCB + FCB + WCB for each WCB that is found.

Any suggestion how to do this in Python?

Regards HoBe

You could store the latest UCB and FCB parents in variables and append to a list on each WCB.

def myFunc(filepath):
    rv = []

    latest_ucb = None
    latest_fcb = None

    with open(filepath, 'r') as file:
        for line in file:
            line = line.lstrip() # remove leading whitespaces
            current_info = line[5:]

            if line[:3] == 'UCB':
                latest_ucb = current_info
            elif line[:3] == 'FCB':
                latest_fcb = current_info
            elif line[:3] == 'WCB':
                rv.append(latest_ucb + latest_fcb + current_info)

    return rv

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