【问题标题】:how to replace a line in a file in python如何在python中替换文件中的一行
【发布时间】:2025-12-10 19:40:01
【问题描述】:

我想替换我的程序创建的文件中的字符串,但我不能使用 .replace,因为它不在 3.3 中,如何使用两个输入(前一个字符串,替换)替换文件中的一行,这里是目前为止的代码吗:

#Data Creator
def Create(filename):
    global UserFile
    UserFile = open(str(filename), "w")
    global file
    file = (filename)
    UserFile.close()

#Data Adder
def Add(data):
    UserFile = open(file, "a")
    UserFile.write(str(data))
    UserFile.close()

#Data seeker
def Seek(target):
    UserFile = open(file, "r")
    UserFile.seek(target)
    global postition
    position = UserFile.tell(target)
    UserFile.close()
    return position

#Replace
def Replace(take,put):
    UserFile = open(file, "r+")
    UserFile.replace(take,put)
    UserFile.close

Create("richardlovesdogs.txt")
Add("Richard loves all kinds of dogs including: \nbeagles")
Replace("beagles","pugs")

我该怎么做才能用“pugs”替换“beagles”这个词? 我正在学习 python,所以任何帮助将不胜感激

编辑:

我把替换代码改成了这个

#Replace
def Replace(take,put):
    UserFile = open(file, 'r+')
    UserFileT = open(file, 'r+')
    for line in UserFile:
        UserFileT.write(line.replace(take,put))
    UserFile.close()
    UserFileT.close()

但在它输出的文件中:

Richard loves all kinds of dogs including: 
pugsles

如何更改它,使其只输出“哈巴狗”而不是“哈巴狗”

【问题讨论】:

标签: python python-3.x


【解决方案1】:

我想到的第一个想法是遍历行并检查给定的行是否包含您要替换的单词。然后只需使用字符串方法 -​​ 替换。当然,最后应该将结果放入/写入文件中。

【讨论】:

  • 这是否意味着将整个文件放入一个字符串然后编辑它?有效地覆盖整个文件?
  • 您可以使用 readlines 方法为给定文件创建行列表,然后您可以遍历该列表。
  • @mic4ael file.readlines 还将整个文件加载到内存中,只需遍历文件对象以一次加载一行。
  • 请注意str.replace 将替换部分单词:'man command'.replace('man', 'woman') 给出了'woman comwomand',这可能不是我们想要的。
【解决方案2】:

也许你想到的是 Unix shell 中的 sed 命令,它可以让你用 shell 本身的替换文本替换文件中的特定文本。

正如其他人所说,在 Python 中替换文本一直是 str.replace()

希望这会有所帮助!

【讨论】:

    【解决方案3】:

    不将整个文件加载到内存中的最快方法是使用file seek, tell and flush。将起始指针设置为位置 0,并在文件中递增 len(replacement_word)。如果几个字节的 sn-p 匹配,那么您在文件中的位置设置一个标记。

    扫描文件后,您可以使用标记重新构建文件,并使用它们之间的替换字符串连接段。

    【讨论】: