【问题标题】:replace certain strings in a file替换文件中的某些字符串
【发布时间】:2014-11-10 13:08:52
【问题描述】:

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

我的代码:

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

请帮我完成我的代码!

【问题讨论】:

    标签: python string file


    【解决方案1】:

    要读/写文件到同一个文件,你需要用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.
    

    顺便说一句,对于给定的字符串,您不需要使用正则表达式。 str.replace 就够了。

    content = content.replace('Hi', 'hi')
    content = content.replace('HELLO', 'hello')
    

    【讨论】:

    • 如果我有一个='hi',我可以content = re.sub('HI', a, content)
    • @user3631292,是的,你可以。或者你可以使用str.replace:content = content.replace('HI', a)
    • @user3631292,如果你的意思是小写大写hicontent = content.replace(a.upper(), a)
    【解决方案2】:

    为此不需要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)
    

    【讨论】:

      猜你喜欢
      • 2018-08-23
      • 2017-08-30
      • 2019-08-27
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2012-03-30
      • 2014-12-13
      相关资源
      最近更新 更多