您的当前位置:首页怎么用Python替换文件中的内容?

怎么用Python替换文件中的内容?

2024-07-17 来源:乌哈旅游

1、Python替换文件中内容代码:

def modify_text():
    with open('test.txt', "r+") as f:
        read_data = f.read()
        f.seek(0)
        f.truncate()   #清空文件
        f.write(read_data.replace('apple', 'android'))
if __name__ == '__main__':
    modify_text()

2、运行前后结果对比

运行前文件:

运行后文件:

显示全文