提问人:MtLeftovers 提问时间:11/5/2023 更新时间:11/6/2023 访问量:43
将对象列表保存到 py 中的文件并从中加载?我不知道从哪里开始
Saving list of objects to and loading from a file in py? I'm not sure where to even start
问:
我开发了一个代码,用于编译从 boppreh 的键盘和鼠标 .hook 功能生成的对象列表,目的是生成和保存基本任务自动化文件。记录和重放操作很容易实现,尽管偶尔仍然有错误,但保存包含对象列表的文件似乎甚至无法接近。酸洗数据似乎是可能的,但我还没有找到足以让我解决抛出的错误的文档。
这是我的整个代码:
import keyboard, mouse, time, pickle, sys
from optparse import OptionParser
events = []
def OnKeyboardEvent(event):
global events
events.append(event)
def OnMouseEvent(event):
global events
# intended extra functionality here later
events.append(event)
def record():
global events
print("Hooking now...")
keyboard.hook(callback=OnKeyboardEvent)
mouse.hook(callback=OnMouseEvent)
print("Hooked.")
keyboard.wait(hotkey='escape')
keyboard.unhook_all()
mouse.unhook_all()
print("Exporting...")
# File IO here
print("Complete.\n")
def play(speed_factor):
global events
# File IO here
print('Playing recorded events...')
# Code below works fine, would love pointers if you have any tho
last_time = None
for event in events:
if speed_factor > 0 and last_time is not None:
time.sleep((event.time - last_time) / speed_factor)
last_time = event.time
if isinstance(event, mouse.ButtonEvent):
if event.event_type == 'up':
mouse.release(event.button)
else:
mouse.press(event.button)
elif isinstance(event, mouse.MoveEvent):
mouse.move(event.x, event.y)
elif isinstance(event, mouse.WheelEvent):
mouse.wheel(event.delta)
else:
key = event.scan_code
if event.event_type == 'down':
keyboard.press(key)
else:
keyboard.release(key)
print('Complete.\n')
def main():
record()
play(2)
if __name__ == "__main__":
main()
我尝试使用 pickle API,但遇到了一个错误,只是简单地说
line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)\[0\]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 65: character maps to \<undefined\>
我试过这个
with open('bin.dat', 'wb') as f:
pickle.dump(events, f)
with open('bin.dat', 'r') as f:
evening = pickle.load(f)
有没有我完全错过的 file-io 方法,或者我应该继续用泡菜把头撞在墙上? 放轻松,我有点新手:))提前谢谢你。
答:
1赞
Gabriel Ramuglia
11/5/2023
#1
使用 pickle 保存和加载对象时,请确保以二进制模式打开文件以进行读取和写入:
with open('bin.dat', 'rb') as f:
events = pickle.load(f)
读取 pickle 文件时,请确保使用 'rb' 模式而不是 'r',以避免解码错误。这应该可以修复您遇到的 UnicodeDecodeError。
来源:我的文章 https://ioflood.com/blog/python-exception/
评论
0赞
MtLeftovers
11/5/2023
感觉有点傻。干杯伙计
0赞
Gabriel Ramuglia
11/5/2023
不用担心!很乐意为您提供帮助!
上一个:在Nim中打开文件
下一个:使用 java 获取目录大小
评论
'rb'
'r'
open()