【发布时间】:2020-03-21 06:51:55
【问题描述】:
我似乎对如何使用字符串、整数和浮点数有点困惑。 我试图读取一个 .txt 文件名 TEST.txt。 这包含:
Hoi
Total: 350
我想为总数添加一个值。 我正在尝试这样:
# open the file
with open("TEST.txt") as f:
# read lines
lines = f.readlines()
# set a sting only to read line 2
string = (lines[2])
# remove the characters from the string
stringNub = string.replace("Total: ","")
print (stringNub)
min = 300
sum3 = int(stringNub) + int(min)
print(sum3)
# replace the string
with open('TEST.txt','r') as file:
filedata = file.read()
filedata = filedata.replace(stringNub,sum3)
with open('TEST.txt','w') as file:
file.write(filedata)
# replace the string
with open('TEST.txt','r') as file:
filedata = file.read()
filedata = filedata.replace(string2,sum3)
with open('TEST.txt','w') as file:
file.write(filedata)
我希望代码会像这样写入 txt:
Hoi
Total: 650
相反,我最终遇到了这个错误: TypeError: replace() 参数 2 必须是 str,而不是 int
但如果我将 int 设为 str,则输出将是 350300。
(我非常喜欢初学者/爱好者)。 我知道代码可能看起来不那么漂亮,但是谁能告诉我我做错了什么?
【问题讨论】:
-
filedata.replace(stringNub, str(sum3))。在替换之前转换为字符串。不需要int(min),因为min已经是一个int。还要避免使用关键字和 stdlib 函数作为变量名。 -
你得到的错误很有表现力。它说参数 2 必须是 str - 非常简单。
-
@Ashwani 就是这样!谢谢。
-
@Austin 我知道这很简单,我仍然缺少一些基础知识,但这有帮助:)
-
@Ashwani 该脚本确实适用于 filedata.replace(stringNub, str(sum3)) 但由于某种原因,它会删除 1 \n 如果后面有任何东西。任何线索为什么会发生这种情况?