作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以如果我有这样的代码:
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/
我是一名优秀的程序员,十分优秀!