从文件中保存和提取变量值

我想实现什么

:

该程序正在寻找文件,如果文件存在,则将文件中的变量值加载到整数变量中,然后添加 1 /多变的 + 1/, 然后通过替换值,再次写入文件

如果文件不存在,则创建文件并将其写入变量的值

这是我试图看看这个网站上另一个程序员提供的示例。


import pickle
import os


PATH = './file.p'

if os.path.isfile/PATH/ and os.access/PATH, os.R_OK/:
print/"file is available to read"/
var1 = pickle.load/open/"file.p","rb"//
print/var1/

pickle.dump/[var1+1], open/"file.p", "wb"//
print /"var+1 is added to the file"/

else:
var1=0;
pickle.dump/[var1], open/"file.p", "wb"//

print/"file is created and var1 added to the file"/


我做错了代码似乎有些问题 ?
已邀请:

知食

赞同来自:

通过更改录制值来修复您的代码 var 在 int, 但不是 list /您将其转换为列表 the[]/. 这是一个新的代码:


import pickle
import os


PATH = './file.p'

if os.path.isfile/PATH/ and os.access/PATH, os.R_OK/:
print/"file is available to read"/
var1 = pickle.load/open/"file.p","rb"//
print/var1/
var0 = var1+1
pickle.dump/var0, open/"file.p", "wb"//

print /"var+1 is added to the file"/

else:
var1=0
pickle.dump/var1, open/"file.p", "wb"//

print/"file is created and var1 added to the file"/


我希望这会有所帮助,祝你好运

要回复问题请先登录注册