微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在课堂中使用 with open

如何解决在课堂中使用 with open

我正在尝试创建一个将数据(数字)附加到 high_scores 的类。

下面的代码将数字附加到 high_scores.dat 并打印 high_scores.dat 的全部内容(以前的数据+新的附加数据)

number = [1]#example
number2 = [2]#example
high_scores_filename = 'high_scores.dat'
scores = [number]

#Here it will append the number to scores
with open(high_scores_filename,"rb") as f:
     unpickler = pickle.Unpickler(f)
     scores = unpickler.load()
     #first_name = (number2) # if i want to append more than 1 object
     score = (number)
     high_scores = score  #,first_name if i want to append more than 1 object
     scores.append(high_scores) #append score to high_score,score = number
# Now we "sync" our database
with open(high_scores_filename,'wb') as wfp:
    pickle.dump(scores,wfp)
# Re-load our database
with open(high_scores_filename,'rb') as rfp:
    scores = pickle.load(rfp)
print(scores)
print("Finished")

在上面的表单中它做我想要的,将 number1 和 number2 附加到 de .dat 文件并打印 .dat 文件内容(就像我运行这个脚本 3 次,我的 . dat 文件第一次有 [1,2] 第二次 [[1,2][1,2]] 第三次 [[1,2]]时间。

但是当我把它放在一个while循环中(所以我可以在其他脚本中调用find_number类)它不会打印分数也不会“完成”让我得出没有奏效的结论。

number = [1]#example
high_scores_filename = 'high_scores.dat'
scores = [number]
class find_number: 
    while True:
        v = pyautogui.locateOnScreen('image.png')#if find this image will do next>
        if v is True:
            #Here it will append the number to scores
            with open(high_scores_filename,"rb") as f:
                unpickler = pickle.Unpickler(f)
                scores = unpickler.load()
                first_name = (number)
                score = (number)
                high_scores = first_name#,score
                scores.append(high_scores)
            # Now we "sync" our database
            with open(high_scores_filename,'wb') as wfp:
                pickle.dump(scores,wfp)
            # Re-load our database
            with open(high_scores_filename,'rb') as rfp:
                scores = pickle.load(rfp)
            print(scores)
            print("Finished")
        else:
            print(v is None)
            break

完整的代码没有给我错误,但是如果我把它当作第二种形式,它并没有做我想要的,而是在第一种形式中做我想做的。

第二种形式返回布尔值True

有人有什么建议吗? 表格我做的表格正确吗? 谢谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。