-1

For example:

300 "FTPAT1  2   " 301 "CHURCH  2   " "01" "Open"   "Line"     
300 "CHURCH  2   " 301 "GREENL1 1   " "01" "Open"   "Line"      
400 "FTPAT1  2   " 401 "CHURCH  2   " "01" "Closed" "Line"     
400 "CHURCH  2   " 401 "GREENL1 1   " "01" "Closed" "Line"    

I want to change the 300-301, "open" to "Closed", and change the 400-401, "closed" to "Open".

So far, what I am doing is:

file = open('testfile.txt', 'r'):
for line in file: 
    print line,

Please help me! Thank you so much.

1
  • Can you post your expected output?
    – Rakesh
    May 21, 2018 at 16:54

1 Answer 1

0

You can use re.sub:

import re
with open('filename.txt') as f:
   with open('new_filename.txt', 'w') as f1:
     f1.write(re.sub('Open|Closed', '{}', f.read()).format(*['Open' if i == 'Closed' else 'Closed' for i in re.findall('Open|Closed', f.read())]))

Output:

300 "FTPAT1 2 " 301 "CHURCH 2 " "01" "Closed" "Line"
300 "CHURCH 2 " 301 "GREENL1 1 " "01" "Closed" "Line"
400 "FTPAT1 2 " 401 "CHURCH 2 " "01" "Open" "Line"
400 "CHURCH 2 " 401 "GREENL1 1 " "01" "Open" "Line"
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.