gpt4 book ai didi

python - 如何在 Python 中重写文本文件

转载 作者:行者123 更新时间:2023-11-28 22:38:47 25 4
gpt4 key购买 nike

所以如果我有这样的代码:

f = open('score.txt','r+')
playersScore = 1
oldscore = (f.read())
oldscore = int(oldscore)
score = oldscore + PlayersScore
f.write(str(score))
f.close()

文本文件中有 1 个。如果我尝试运行代码,它会给出此错误:

oldscore = int(oldscore)
ValueError: invalid literal for int() with base 10: ''

我该如何解决这个问题?我是 Python 初学者,所以请保持简单。

最佳答案

我认为问题是由添加新行而不是替换旧行引起的。这应该有效:

f = open('score.txt','r+')
playersScore = 1
oldscore = (f.read())
oldscore = int(oldscore)
score = oldscore + playersScore
f.seek(0)
f.write(str(score))
f.close()

关于python - 如何在 Python 中重写文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35385601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com