0

I'm attempting to write my first Python script for QGIS. I have no programming experience and am having some difficulty.

The aim is to loop through a folder and check to see if the file name contains the string "rsa2". If it does, copy the file path to an existing attribute called "rsa2_document" for each feature in a shapefile.

I've been using this as an example of how to change attributes with a script but I'm getting the following error: name 'folder_containing_files' is not defined See log for more details. Since I'm completely new to this, I can't tell if the error message is not being helpful and it's a problem with my code or if there is some sort of issue with using a folder type input. I looked here for an idea of how to use the folder type input, but doesn't say if the folder type input gives a string or an object.

My code so far is below. I'm using QGIS 2.8.2 on Windows 7.

##inlayer=vector
##folder_containing_files = folder

from qgis.core import *
from PyQt4.QtCore import *
import os

for file in os.walk(folder_containing_files):
    if string(file).contains("rsa 2"):
        path = file

layer = processing.getObject(inLayer)
for feat in layer.getFeatures():
    outlayer.changeAttributeValue(feat.id(), rsa_2_document, path)

outlayer.commitChanges()

1 Answer 1

2

Your code is wrong for several reasons: - os.walk returns a complex object, not a string - you don't have an outlayer defined - you didn't define the field you want to fill ...

The following code should work for a folder with no subdirectories:

##inlayer=vector
##folder=folder

import os
import processing

#get the path of the file in the 'path' variable
for file in os.listdir(folder):
    if file.find('rsa_2') != -1 :
        print file
        path = folder+'/'+file


#fill the 'rsa_2' field with the path for every feature of inlayer
layer = processing.getObject(inlayer)
layer.startEditing()
field = layer.fieldNameIndex('rsa_2')
for feat in layer.getFeatures():
    layer.changeAttributeValue(feat.id(), field, path)

layer.commitChanges()

Not the answer you're looking for? Browse other questions tagged or ask your own question.