view flys-backend/contrib/shpimporter/utils.py @ 4874:b1d7e600b43b

(importer) Add utility function to convert paths to utf-8 - Add utility function to generically copy fields
author Andre Heinecke <aheinecke@intevation.de>
date Fri, 25 Jan 2013 10:41:09 +0100
parents 59ca5dab2782
children e9880b224c2f
line wrap: on
line source
import os
import sys
from shpimporter import DEBUG, INFO, ERROR

SHP='.shp'

def findShapefiles(path):
    shapes = []

    for root, dirs, files in os.walk(path):
        if len(files) == 0:
            continue

        DEBUG("Processing directory '%s' with %i files " % (root, len(files)))

        for f in files:
            idx = f.find(SHP)
            if (idx+len(SHP)) == len(f):
                shapes.append((f.replace(SHP, ''), root + "/" + f))

    return shapes

def getUTF8Path(path):
    """
    Tries to convert path to utf-8 by first checking the filesystemencoding
    and trying the default windows encoding afterwards.
    Returns a valid UTF-8 encoded unicode object or throws a UnicodeDecodeError
    """
    try:
        return unicode.encode(unicode(path, sys.getfilesystemencoding()), "UTF-8")
    except UnicodeDecodeError:
        # Probably Windows iso-8859-x names so lets try again
        return unicode.encode(unicode(path, "iso-8859-15"), "UTF-8")

def copyFields(src, target, mapping):
    """
    Checks the mapping dictonary for key value pairs to
    copy from the source to the destination feature.

    The Key is the attribute of the source feature to be copied
    into the target attribute named by the dict's value.
    """
    for key, value in mapping.items():
        if src.GetFieldIndex(key) == -1:
            continue
        if src.IsFieldSet(src.GetFieldIndex(key)):
            if src.GetFieldType(key) == 2:
                target.SetField(value, src.GetFieldAsDouble(key))
            else:
                target.SetField(value, src.GetField(key))

http://dive4elements.wald.intevation.org