如何将列表保存到文本文件?

时间:2017-09-03 07:47:04

标签: python-2.7 list pickle qgis cpython

我想将所有x ad 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?

1 个答案:

答案 0 :(得分:1)

最简单的方法是放弃使用QgsPoint(xp, yp)并使用元组,即只使用(xp, yp)。似乎QgsPoint是C ++类的SIP包装器;和SIP包装器不会知道酸洗。

另请注意pyqgis documentation说:

  

注意

     

元组(x,y)不是真正的元组,它们是QgsPoint个对象,可以使用x()y()方法访问这些值。

它们看起来像元组,但它们并不像元组一样,甚至无法使用t[0]访问单个坐标。

也就是说,您可以使用

轻松地将这些点列表转换为元组列表
lst = [(p.x(), p.y()) for p in lst]
pickle.dump(lst, handle)