简体   繁体   中英

How to replace certain parts of text in text file?

I need to read through every line in a text file and replace every line with the string "+44" in it with "0".. Basically replace "+44" with "0" but keep the rest of the line exact same

My code:

f = open("Pajanimals.txt",'r')

for line in f:
    if '+44' in line:

There's no point in checking each line - just replace everything in one go:

path = 'Pajanimals.txt'
try:
    with open(path, 'r') as infile:
        data = infile.read().replace('+44', '0')
except OSError as exception:
    print('ERROR: could not read file:')
    print('  %s' % exception)
else:
    with open(path, 'w') as outfile:
        outfile.write(data)

You can simply use string.replace here:

for line in f:
    new_number = line.replace("+44", "0")

If you were doing something more complicated, I would probably recommend a regular expression, but your case is very simple.

The only thing to note here is that replace will all the instances it finds, so "+44123+44" would become "01230" , but there is a maxreplace argument you can use to limit it to the first instance:

line.replace("+44", "0", 1)

Would transform "+44123+44" to "0123+44"

Try this:

f = open('Pajanimals.txt','rt')
lines = f.readlines()
f.close()

f = open('Pajanimals.txt','wt')
f.writelines([line.replace('+44','0') for line in lines])
f.close()

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