python学习笔记——修改文本内容

python无法直接修改文本中的内容,通过将原文本导入内存中编辑后重新以“W”方法打开文本再写入实现修改。

    old_file = ""  # 变量用以存放文本内容
    with open(file, 'r', encoding='utf-8') as f:
        for line in f:
            if key_str in line:  # 通过key_str变量定位需要修改的行
                line = line.replace(old_str, new_str)
            old_file += line  
    with open(file, 'w', encoding='utf-8') as f:  # ‘w’方式意味着打开一个空白的文件,并覆盖原同名文件。
        f.write(old_file)


磁盘文件-》内存变量-》遍历、切割、定位-》修改内存变量-》重写磁盘文件

原文地址:https://www.cnblogs.com/ChenYi0919/p/8866758.html