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

2024-10-03 21:24:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的代码:

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

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

Tags: 字符串代码intxtforiflineopen
3条回答

试试这个:

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()

您只需在此处使用string.replace

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

如果您要执行更复杂的操作,我可能会建议使用正则表达式,但您的情况非常简单。在

这里唯一要注意的是replace将所有它找到的实例,因此"+44123+44"将变成{},但是有一个maxreplace参数可以用于将其限制为第一个实例:

^{pr2}$

"+44123+44"转换为"0123+44"

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

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)

相关问题 更多 >