How I can skip first header line? I have headers duplicated later in the code, so I can eliminate them by if not l.startswith('MANDT') but first header I want to keep. How I need to modify the code?
keep -> MANDT|BUKRS|NETWR|UMSKS|UMSKZ|AUGDT|AUGBL|ZUONR
100|1000|23.321-|||||TEXT
100|1000|0.12|||||TEXT
100|1500|90|||||TEXT
remove -> MANDT|BUKRS|NETWR|UMSKS|UMSKZ|AUGDT|AUGBL|ZUONR
100|1000|23.321-|||||TEXT
100|1000|0.12|||||TEXT
100|1500|90|||||TEXT
remove -> MANDT|BUKRS|NETWR|UMSKS|UMSKZ|AUGDT|AUGBL|ZUONR
Code I am using.
with open('yourfile.txt', 'r+') as f: # 'r+' - read/write mode
lines = f.read().splitlines()
f.seek(0) # reset file pointer
f.truncate() # truncating file contents
for l in lines:
if not l.startswith('---'):
# or f.write('|'.join(map(str.strip, l.strip('|').split('|'))) + '\n')
f.write(re.sub(r'\|\s*|\s*\|', '|', l).strip('|') + '\n')
If your motto is to remove all lines starting with the keyword
MANDT
, except for the first line then this will work fine.