简体   繁体   中英

find and replace whole line python

I have a file like this..

xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
a b c invalid #seperated by tab
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx

I need to replace abc invalid to ab reviewed rd # separated by tab Basically any line that ends with invalid, I need to replace that line with reviewed rd // separated by tab but I have to keep the first and second words on that line (only replace 3rd and 4th).

I have started doing something like this, but this won't exactly do what I want.

f1 = open('fileInput', 'r')
f2 = open('fileInput'+".tmp", 'w')
for line in f1:
    f2.write(line.replace('invalid', ' reviewed'+\t+'rd'))
f1.close()
f2.close()

regex can be an option but I'm not that good with it yet. Can someone help.

PS a,b and c's are variables.. I can't do an exact search on 'a','b','c'.

f1 = open('fileInput', 'r')
f2 = open('fileInput+".tmp"', 'w')
for line in f1:
    if line[:-1].endswith("invalid"):
        f2.write("\t".join(line.split("\t")[:2] + ["reviewed", "rd"]) + "\n")
    else:
        f2.write(line)
f1.close()
f2.close()
import re

pattern = re.compile(r'\t\S+\tinvalid$')
with open('data') as fin:
    with open('output', 'w') as fout:
        for line in fin:
            fout.write(pattern.sub('\treviewd\trd', line))
with open('input.tab') as fin, open('output.tab', 'wb') as fout:
    tabin = csv.reader(fin, delimiter='\t')
    tabout = csv.writer(fout, delimiter='\t')
    for row in tabin:
        if len(tabin) != 4:
            continue # or raise - whatever
        if row[-1] == 'invalid':
            tabout.writerow(row[:2] + ['reviewed', 'rd'])

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