python - 截断“空格”问题 x/002
问题描述
import re
with open("./teste/counter.txt", "r+") as count:
countread = count.read()
inputvar = input("Counting - write anything: ")
if countread == "":
print("Countread is ''None''. Adding to text file number ''1''.")
count.write('1')
else:
count.truncate(0)
countread = countread.replace(' ', '')
countplus = int(countread) + 1
print(countread)
count.write(str(countplus))
count.close()
我正在尝试使用 count.truncate(0) 擦除文件,但在它添加 1 并在我的文本文件中转到 2 后,在 3 处出现错误:
ValueError: invalid literal for int() with base 10: '\x002'
对于行''countplus = ...''
编辑:顺便说一下,''countread replace'' 是为了解决这个问题。
解决方案
用这个修复它
while 3>2:
with open("./teste/counter.txt", "r+") as count:
countread = count.read()
if countread == "":
countread = "0"
inputvar = input("Counting " + countread + " write anything: ")
if countread == "0":
count.write('1')
else:
countplus = int(countread) + 1
count.truncate(0)
count.seek(0)
countread = count.read()
count.write(str(countplus))
count.close()
推荐阅读
- javascript - 实现一个 Vue.js 组件,以便将元素定义为
- cassandra - Cassandra 3.11,按列表过滤结果(搜索替代品)
- postgresql - PostgreSQL - dblink_exec statement_timeout
- c# - Xamarin Forms 嵌套 flex 布局与其他控件无法正确呈现
- javascript - 如何将放置在reactjs中的json对象内的图像发布到spring boot后端rest api
- python - 使用 scikit learn 在 python 中进行管道和交叉验证
- .net - 如何自动启动使用 Msix 打包的应用程序?
- key-value - etcd 是否将其 key-value 数据直接存储在 Raft 日志中?
- c# - c#脚本Roslyn会话不接受参考
- javascript - 尝试在生产中的反应应用程序中添加自定义 HTML 和 JS 代码