Python 替换文件中的某些字符串

Python 替换文件中的某些字符串,python,string,file,Python,String,File,我有一个文本文件,我需要用一些字符串替换它。我需要将它写入文件。 问题 在不更改缩进和间距的情况下,如何将文件上替换的字符串写入另一个文件/同一个文件 我的代码: a='hi' b='hello' with open('out2','r') as f: if 'HI' in f: m = re.sub(r'HI', a) if 'HELLO' in f: m = re.sub(r'HELLO', b) out2.close() 请帮我完成我的代码 要将文件读/写到同一文件,

我有一个文本文件,我需要用一些字符串替换它。我需要将它写入文件。 问题 在不更改缩进和间距的情况下,如何将文件上替换的字符串写入另一个文件/同一个文件

我的代码:

a='hi'
b='hello'
with open('out2','r') as f:
 if 'HI' in f:
    m = re.sub(r'HI', a)
 if 'HELLO' in f:
    m = re.sub(r'HELLO', b)
out2.close()

请帮我完成我的代码

要将文件读/写到同一文件,您需要使用
r+
模式打开该文件

字符串替换应针对字符串而不是文件进行。读取文件内容并替换字符串,然后将替换的字符串写回

with open('out2', 'r+') as f:
    content = f.read()
    content = re.sub('HI', 'hi', content)
    content = re.sub('HELLO', 'hello', content)
    f.seek(0)  # Reset file position to the beginning of the file
    f.write(content)
    f.truncate()  # <---- If the replacement string is shorter than the original one,
                  #       You need this. Otherwise, there will be remaining of
                  #         content before the replacement.

这不需要
Regex
。您只需按照以下方式进行操作:

with open('out2','r') as f:
  with open('outFile','w') as fp:  
    for line in f:
      line=line.replace('HI','hi')
      line=line.replace('HELLO','hello')
      fp.write(line)

如果我有一个class='hi',我可以做
content=re.sub('hi',a,content)
@user3631292,是的,你可以。或者您可以使用
str.replace
content=content.replace('HI',a)
@user3631292,如果您想使用大写字母
HI
content=content.replace(a.upper(),a)
with open('out2','r') as f:
  with open('outFile','w') as fp:  
    for line in f:
      line=line.replace('HI','hi')
      line=line.replace('HELLO','hello')
      fp.write(line)