首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何用Python 3替换文本文件中字符串的所有实例?

如何用Python 3替换文本文件中字符串的所有实例?
EN

Stack Overflow用户
提问于 2018-06-20 06:11:50
回答 1查看 800关注 0票数 0

我正在尝试替换文本文件中给定字符串的所有实例。我试图逐行读取文件,然后使用replace函数,但它只是输出一个空文件,而不是预期的文件。我能做错什么呢?

file = input("Enter a filename: ")
remove = input("Enter the string to be removed: ")

fopen = open(file, 'r+')
lines = []

for line in fopen:
    line = line.replace(remove,"")

fopen.close()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-20 09:00:02

试试这个:

# Make sure this is the valid path to your file
file = input("Enter a filename: ")
remove = input("Enter the string to be removed: ")

# Read in the file
with open(file, "r") as file:
    filedata = file.read()

# Replace the target string
filedata = filedata.replace(remove, "")

# Write the file out again
with open(file, "w") as file:
    file.write(filedata)

注意:您可能想要使用with open语法,Jason Sundram在这篇answer中详细阐述了它的好处。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50937625

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档