如何在python中替换文件中的行

如何在python中替换文件中的行,python,python-3.x,Python,Python 3.x,我想替换程序创建的文件中的一个字符串,但我无法使用。替换因为它不在3.3中,如何使用两个输入(前一个字符串,替换)替换文件中的一行,以下是到目前为止的代码: #Data Creator def Create(filename): global UserFile UserFile = open(str(filename), "w") global file file = (filename) UserFile.close() #Data

我想替换程序创建的文件中的一个字符串,但我无法使用。替换因为它不在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")
我该怎么做,让它用“哈巴狗”取代“小猎犬”这个词? 我正在学习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

如何更改它,使其只输出“pugs”而不输出“pugsles”

我想到的第一个想法是在行上循环,检查给定行是否包含要替换的单词。然后只需使用string方法-replace。当然,最终结果应该被放入/写入文件。

也许您想到的是Unix shell中的
sed
命令,它将允许您用shell本身的替换文本替换文件中的特定文本

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


希望这有帮助

在不将整个文件加载到内存的情况下,执行此操作的最快方法是使用
文件查找、通知和刷新
。将起始指针设置为位置0,并通过
len(替换词)
在文件中递增。如果几个字节的代码段匹配,则在文件中的位置设置一个标记


扫描文件后,可以使用标记重新生成文件,并使用替换字符串连接段。

file.replace
在python中从未出现。
str.replace()
是一种字符串方法。它不是文件对象上的方法。从来没有。我肯定我在什么地方读过,一定是弄错了。那还有什么别的办法呢?@Jaffar Start here:;相关:可能重复这是否意味着将整个文件放入字符串中,然后编辑它?有效覆盖整个文件?您可以使用readlines方法为给定文件创建行列表,然后您可以在列表上循环。@mic4ael
file。readlines
也会将整个文件加载到内存中,只需在文件对象上迭代,一次加载一行。请注意,
str.replace
将替换部分单词:
'man command'。