【发布时间】: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
如何更改它,使其只输出“哈巴狗”而不是“哈巴狗”
【问题讨论】:
-
file.replace从未出现在 python 中。 -
str.replace()是 strings 上的方法。它不是文件对象的方法。从来没有。 -
我确定我在某处读过它,一定是错的还有什么其他方法吗?
-
@Jaffar 从这里开始:docs.python.org/3/tutorial/…;相关:find and replace within a text file
标签: python python-3.x