问题描述:
在阅读代码的过程中,有需要进行.pkl文件的load操作,但是我们能获取到的是字符串文件(.txt)文件,直接读取.txt文件,报错,信息如下:_pickle.UnpicklingError: invalid load key, 'H'.
尝试解决方法(没有解决问题的方法):
代码① + 运行命令①
运行命令②
代码①
#!/usr/bin/env python
"""\
convert dos linefeeds (crlf) to unix (lf)
usage: dos2unix.py <input> <output>
"""
import sys
if len(sys.argv[1:]) != 2:
sys.exit(__doc__)
content = ''
outsize = 0
with open(sys.argv[1], 'rb') as infile:
content = infile.read()
with open(sys.argv[2], 'wb') as output:
for line in content.splitlines():
outsize += len(line) + 1
output.write(line + b'\n')
print("Done. Saved %s bytes." % (len(content)-outsize))
运行命令①
# usage: dos2unix.py <input> <output>
python dos2unix.py srcFile.pkl destFile.pkl
运行命令②
vim srcFile.pkl -c "set ff=unix" -c ":wq"
最终解决方法(解决了问题):
思路解说:先将
.txt文件/包含字符串文件用pickle.dump()方法写入到.pkl文件,再去操作该文件
★ 文件级操作
srcFile内容(srcFile.txt内容)
name fruit1 fruit2 fruit3
fruitName: apple mongo carrot
import pickle
destFile = 'destPickle.pkl'
with open("srcFile", "r") as fh:
long_content = fh.read()
f = open(destFile, 'wb')
pickle.dump(long_content, f)
f.close()
f = open(destFile, 'rb')
storedFile = pickle.load(f)
# print(storedFile)
☆ 代码内部操作(.py脚本内部直接操作)
import pickle
srclist = ['apple', 'mango', 'carrot']
print(srclist)
f = open(destlist, 'wb')
pickle.dump(srclist , f)
f.close()
del srclist
f = open(destlist, 'rb')
storedFile = pickle.load(f)
print(storedFile)