Skip to main content
 首页 » 编程设计

python之如何替换文本文件中的某些文本部分

2024年10月24日10itcoder

我需要通读文本文件中的每一行,并将其中的字符串“+44”替换为“0”。基本上将“+44”替换为“0”,但保留该行的其余部分完全一样

我的代码:

f = open("Pajanimals.txt",'r') 
 
for line in f: 
    if '+44' in line: 

请您参考如下方法:

检查每一行没有意义 - 只需一次性替换所有内容:

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)