即使在我关闭 python 程序后,我如何保持计数保持正确的数字
How do I keep a count that stays on the correct number even after I close the python program
我想出了一个解决方案,我最初可以只包含一个包含 0 的文本文件,每次我使用该程序时,我都会将文本文件中的数字增加 1,然后读取文本文件以轮流获取数字,但似乎有错误。
该代码是第一次运行,它将 1 添加到 0 并使其变为 1,但在它之前添加了一些空格,我使用了替换命令但仍然遇到错误。
我的代码如下:
"def count_incr():
f=open("entry count.txt","r+")
v=f.readlines()
for i in v:
count=int(i)
count+=1
count=str(count)
count.replace(" ","")
f.truncate(0)
f.write(count)
f.close()
count_incr()"
错误如下:
"回溯(最近调用最后):
文件“C:\Users\Technical Gossip\Desktop\Project\Input and insertion.py”,第 27 行,在
count_incr()
文件“C:\Users\Technical Gossip\Desktop\Project\Input 和 insertion.py”,第 19 行,在 count_incr 中
计数=整数(我)
ValueError:以 10 为底的 int() 的无效文字:'\x001'"
truncate
更改文件的长度但不倒回它。当您写入新计数时,您仍然位于旧文件的末尾。操作系统会帮助用零字节填充到那个点。
而不是 truncate
,使用 f.seek(0)
。您可以考虑添加换行符,但这取决于您。
我想出了一个解决方案,我最初可以只包含一个包含 0 的文本文件,每次我使用该程序时,我都会将文本文件中的数字增加 1,然后读取文本文件以轮流获取数字,但似乎有错误。 该代码是第一次运行,它将 1 添加到 0 并使其变为 1,但在它之前添加了一些空格,我使用了替换命令但仍然遇到错误。
我的代码如下:
"def count_incr():
f=open("entry count.txt","r+")
v=f.readlines()
for i in v:
count=int(i)
count+=1
count=str(count)
count.replace(" ","")
f.truncate(0)
f.write(count)
f.close()
count_incr()"
错误如下:
"回溯(最近调用最后): 文件“C:\Users\Technical Gossip\Desktop\Project\Input and insertion.py”,第 27 行,在 count_incr() 文件“C:\Users\Technical Gossip\Desktop\Project\Input 和 insertion.py”,第 19 行,在 count_incr 中 计数=整数(我) ValueError:以 10 为底的 int() 的无效文字:'\x001'"
truncate
更改文件的长度但不倒回它。当您写入新计数时,您仍然位于旧文件的末尾。操作系统会帮助用零字节填充到那个点。
而不是 truncate
,使用 f.seek(0)
。您可以考虑添加换行符,但这取决于您。