【问题标题】:How to replace all instances of a string in text file with Python 3?如何用 Python 3 替换文本文件中字符串的所有实例?
【发布时间】:2018-11-28 23:04:55
【问题描述】:

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

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()

【问题讨论】:

  • 文件修改。我可以很好地打印这些行,但由于某种原因实际上覆盖文件中的初始数据时遇到了麻烦。它要么在文件末尾追加新文本,要么完全空白文件。

标签: string python-3.x file input output


【解决方案1】:

试试这个:

# 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 中进行了详细说明。

【讨论】:

    猜你喜欢
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2021-02-08
    • 2021-08-16
    相关资源
    最近更新 更多