品易云推流 关闭
文章详情页
文章 > Python常见问题 > 怎么用Python替换文件中的内容?

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

头像

 Ly

2020-05-26 11:57:023968浏览 · 0收藏 · 0评论

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、运行前后结果对比

运行前文件:

p1.jpg

运行后文件:

p2.jpg

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图