How to export attributes from QGIS to a .txt file using Python

In this task we will see how to get the attributes of a vector layer and export them in a text file. Furthermore, at the end of the task we will order these attributes alphabetically before writing them in the output file.

As a sample, we will use the vector layer that we have filtered in a previous task. This layer represents the cities with more than one million people (data source: Natural Earth):

set

We assume that the above layer is already loaded in the QGIS Layers Panel.

The purpose of the task is to store the name of each city and its corresponding population in a text file. For doing that, we need to extract the informations that are contained in the attributes “name” and “pop_max”, as you can see if you select the Identify tool and click on any of the points to examine the available attributes:

attributes

If we are not interested in the order in which the attributes are exported, we can use the following code (if you don’t know how to create a custom script, please see here):

##input_file=vector

from qgis.core import *
import processing
# Load the layer
layer = processing.getObject(input_file)

# Set the path for the output file
output_file = open('C:/.../cities.txt', 'w')

# Get the features and properly rewrite them as lines
for feat in layer.getFeatures():
    msgout = '%s, %s\n' % (feat["name"], feat["pop_max"])
    unicode_message = msgout.encode('utf-8')
    output_file.write(unicode_message)
output_file.close()

This will be the result:

cities_notordered

If we want to alphabetically sort the attributes before writing them in the output file, we can coding in this way:

##input_file=vector

from qgis.core import *
import processing
# Load the layer
layer = processing.getObject(input_file)

# Set the path for the output file
output_file = open('C:/.../cities.txt', 'w')

# Get the features
feats = []
for feat in layer.getFeatures():
    msgout = '%s, %s\n' % (feat["name"], feat["pop_max"])
    unicode_message = msgout.encode('utf-8')
    feats.append(unicode_message)

# Sort the features
feats.sort()

# Write the features in the output file
for item in feats:
    output_file.write(item)
output_file.close()

This will be the result:

cities_ordered

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s