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
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.