Ubuntu – How to get the (XDG) Default User Directories from Python

pythonxdgxdg-base-directory

By example,
In English the default user folders will be:

$HOME/Desktop
....
$HOME/Videos

In Spanish the default user folders will be:

$HOME/Escritorio
....
$HOME/VĂ­deos

The file ~/.config/user-dirs.dirs has those localize names for the default folders. (Always?).

I need to get those names from a python script. I'd like not to parse that file. Is there other elegant way?
I found this:

from xdg.BaseDirectory import *
print xdg_cache_home
print xdg_config_dirs
print xdg_config_home
print xdg_data_dirs
print xdg_data_home

But it doesn't return those folders.

Thanks in advance!

Best Answer

If you don't mind getting a dependency on GLib or if you're already using GTK as toolkit, you can use the GLib.get_user_special_dir() method.

>>> from gi.repository import GLib
>>> GLib.get_user_special_dir(GLib.USER_DIRECTORY_PICTURES)
'/home/timo/Afbeeldingen'
>>> GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOCUMENTS)
'/home/timo/Documenten'
>>> GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOWNLOAD)
'/home/timo/Downloads'

All available directories:

G_USER_DIRECTORY_DESKTOP         the user's Desktop directory
G_USER_DIRECTORY_DOCUMENTS       the user's Documents directory
G_USER_DIRECTORY_DOWNLOAD        the user's Downloads directory
G_USER_DIRECTORY_MUSIC           the user's Music directory
G_USER_DIRECTORY_PICTURES        the user's Pictures directory
G_USER_DIRECTORY_PUBLIC_SHARE    the user's shared directory
G_USER_DIRECTORY_TEMPLATES       the user's Templates directory
G_USER_DIRECTORY_VIDEOS          the user's Movies directory
G_USER_N_DIRECTORIES             the number of enum values

If you get this error message:

ImportError: When using gi.repository you must not import static modules like "gobject". Please change all occurrences of "import gobject" to "from gi.repository import GObject".

You need to use this:

import glib
return glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES)