【发布时间】:2018-02-11 18:18:50
【问题描述】:
我想将所有 x 和 y 坐标(栅格图层中的每个像素居中)保存为文本文件中的列表。首先进行测试,我在下面写了正确的代码:
import os
import pickle
mylist = [(12, 25), (65, 96), (10, 15)]
path = r"data/listfile"
file = 'file.txt'
if not os.path.exists(path):
os.makedirs(path)
with open(os.path.join(path, file), 'wb') as handle:
pickle.dump(mylist, handle)
with open(os.path.join(path, file), 'rb') as handle:
aa = pickle.loads(handle.read())
print aa
在下一步中,我将这段代码实际用于我的栅格图层。该代码的 MCVE 是:
from qgis.core import *
from PyQt4 import *
import os
import pickle
ds = QgsRasterLayer("/LData/Pop/lorst.tif", "Raster")
pixelWidth = ds.rasterUnitsPerPixelX()
pixelHeight = ds.rasterUnitsPerPixelY()
originX, originY = (ext.xMinimum(), ext.yMinimum())
src_cols = ds.width()
src_rows = ds.height()
path = r"LData/Pop"
file = 'List.txt'
if not os.path.exists(path):
os.makedirs(path)
def pixel2coord(x, y):
xp = (pixelWidth * x) + originX + (pixelWidth / 2)
yp = (pixelHeight * y) + originY + (pixelHeight / 2)
return QgsPoint(xp, yp)
list =[]
for i in range(0, src_cols):
for j in range(0, src_rows):
rspnt = pixel2coord(i, j)
list.append(rspnt)
with open(os.path.join(path, file), 'wb') as handle:
pickle.dump(list, handle)
with open(os.path.join(path, file), 'rb') as handle:
lst = pickle.loads(handle.read())
但是我收到了这个错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/tmp/tmp4rPKQ_.py", line 70, in <module>
pickle.dump(pntRstList, handle)
File "/usr/lib/python2.7/pickle.py", line 1376, in dump
Pickler(file, protocol).dump(obj)
File "/usr/lib/python2.7/pickle.py", line 224, in dump
self.save(obj)
File "/usr/lib/python2.7/pickle.py", line 286, in save
f(self, obj) # Call unbound method with explicit self
File "/usr/lib/python2.7/pickle.py", line 606, in save_list
self._batch_appends(iter(obj))
File "/usr/lib/python2.7/pickle.py", line 621, in _batch_appends
save(x)
File "/usr/lib/python2.7/pickle.py", line 306, in save
rv = reduce(self.proto)
File "/usr/lib/python2.7/copy_reg.py", line 71, in _reduce_ex
state = base(self)
TypeError: the sip.wrapper type cannot be instantiated or sub-classed
有什么方法可以将 xy 列表转换为文本文件并以数字格式而不是 str 格式回读?
【问题讨论】:
-
您可能需要编写自己的代码来进行序列化(和解析)
-
因为
sip.wrapper不能被实例化或子类化,所以你不能腌制这些。您需要用其他东西替换它们。但是您没有在问题中提供 MCVE,所以这个问题无法回答 -
另外,您没有存储在文本文件中,该字典不会导致 pickle 错误
-
@nickan 你需要提供一个minimal reproducible example!这几乎不是最小的。当你这样做时,你需要添加完整的异常回溯。
-
@nickan 抱歉,没有。这不是一个可验证的例子。当我运行它时,我得到了一个例外。我修复它,我得到另一个,然后另一个,然后另一个......请编写一段代码,当保存在 file 中时 run 会产生错误。注意你是如何分配给
mydict然后腌制distDict。
标签: python-2.7 list pickle qgis cpython