我可以獲取文件中的所有對象。這是我遇到的錯誤:with open("Resultfill", "rb") as Resultfillread: FileNotFoundError: [Errno 2] No such file or directory: 'Resultfill'這意味著該文件不存在。由于下面的答案,這個問題已經解決。但我總是無法訪問文件中包含的對象,特別是使用yield. 這是文件二進制文件“testfile”中包含的對象di = {"c1": 3, "c2": 5, "c3": 13, "c4": 12, 5: 8, 6: 8, 7: 1, 8: 5, 9: 12, 10: 2, 11: 20, 12: 16, 13: 45, 14: 6, 15: 4 }di = {1: 3, 2: 5, 3: 13, 4: 12, 5: 8, 6: 8, 7: 1, 8: 5, 9: 12, 10: 2, 11: 20, 12: 16, 13: 45, 14: 6, 15: 4 }這是代碼:os.chdir("C:/Program Files/Sublime Text 3/testpython")open("testfile", "ab")def loadobject(fillname): with open(filename, "rb") as test: while True: try: yield pickle.load(test) except EOFError: breakgenaratetest = loadobject("testfile")print(Resultfillwrite)for testobject in genaratetest: print(testobject)我希望 print(testobject) 每次循環打印一個對象,在本例中,第一個字典“di”,然后是第二個。
1 回答

蕭十郎
TA貢獻1815條經驗 獲得超13個贊
如果您正在編寫一個新文件,如果該文件不存在,則會創建該文件,但open("Resultfill", "rb")
您已經說過要從該文件中讀取內容。創建一個新文件然后嘗試從中讀取沒有多大意義,因此您會收到錯誤。
如果您嘗試讀取某個文件,請確保該文件存在并且您使用的是正確的路徑。
如果您嘗試創建新文件或覆蓋現有文件,請使用open("Resultfill", "wb")
添加回答
舉報
0/150
提交
取消