'in-place' string modifications in Python

后端 未结 14 1541
一整个雨季
一整个雨季 2020-12-05 23:38

In Python, strings are immutable.

What is the standard idiom to walk through a string character-by-character and modify it?

The only methods I can think of a

14条回答
  •  囚心锁ツ
    2020-12-06 00:04

    I did that like this:

    import tempfile
    import shutil
    
    ...
    
    f_old = open(input_file, 'r')
    with tempfile.NamedTemporaryFile() as tmp:
        for line in f_old:
            tmp.write(line.replace(old_string, new_string))
        f_old.close()
        tmp.flush()
        os.fsync(tmp)
        shutil.copy2(tmp.name, input_file)
        tmp.close()
    

提交回复
热议问题