如何编辑和修改?

2024-09-30 12:15:21 发布

您现在位置:Python中文网/ 问答频道 /正文

据我所知,在pickle文件中编辑对象的唯一方法是取消拾取每个对象,编辑所需对象,然后将所有内容重新拾取回原始文件

这就是我尝试做的:

pickleWrite = open(fileName, 'wb')
pickleRead = open(fileName, 'rb')

#unpickle objects and put it in dataList

dataList = list()

try:
  while True:
    dataList.append(pickle.load(pickleRead))
except EOFError:
  pass

#change desired pickle object

dataList[0] = some change

#clear pickle file
pickleWrite.truncate(0)

#repickle each item in data list

for data in dataList:
  pickle.dump(data, fileName)

出于某种原因,这使得pickle文件在文件前面有大量未知符号,因此无法对其进行pickle

尝试取消勾选时出错:

_pickle.UnpicklingError: invalid load key, '\x00'.

Tags: 文件对象方法in编辑dataloadopen
1条回答
网友
1楼 · 发布于 2024-09-30 12:15:21

我建议避免像这样对同一个文件创建多个打开的连接

相反,您可以尝试:

# Read the contents
with open(filename, 'rb') as file:
  dataList = pickle.load(file)

# something to dataList

# Overwrite the picle file
with open(filename, 'wb') as file:
  pickle.dump(dataList, file)

相关问题 更多 >

    热门问题