我正在尝试替换文本文件中给定字符串的所有实例。我试图逐行读取文件,然后使用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()
发布于 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中详细阐述了它的好处。
https://stackoverflow.com/questions/50937625
复制相似问题