# How to get the directory of open blend file? (from Python)

What's the best way to get the full directory of the current Blender file in Python?

It should be cross-platform.

• blender.stackexchange.com/questions/2545/… – stacker Feb 7 '14 at 11:49
• @stacker, I was hoping for something cleaner. Both Adhi and iKIsR's answers would return the whole filepath including filename. I'd have to split the string using '/' for Linux/Mac and '\\', then strip it off the end. Is there not a single command to get the directory? – Garrett Feb 7 '14 at 11:55
• Python as well as Blender provide path util functions, you shouldn't ever split using / and \. Or at least use os.path.sep to get the separator for the current platform. But keep in mind Blender's own notation for relative paths (starting with //). And always check windows compatibility, python may fail for paths which are directly on a drive (drive missing the colon or the backslash). – CodeManX Feb 7 '14 at 14:01

Path Utilities module provides bpy.path.abspath("//") where the "//" prefix is a Blender specific identifier for the current blend file.

You can also do...

• bpy.path.abspath("//my/file.txt")
• bpy.path.abspath("//my\\file.txt") on Windows, with backslash escaped
• bpy.path.abspath(r"//my\file.txt") on Windows, using python raw string
• bpy.path.abspath("//../file.txt") to go back a directory

This is used by all internal paths in blender, image, video, render, pointcache etc - paths. so blend files can reference paths relative to each file.

Worth noting that the path may be an empty string, so you may want to check bpy.data.is_saved first.

• you missed to escape the backslash, edited your answer to show two ways to handle them. General note: with raw strings, you can't have a \  as last character, nor can you escape it like \\  (will be used literally, as double backslash, repr(r"\\") gives \\\\ ). [had to add a space after \ for stackexchange] – CodeManX Feb 7 '14 at 16:51

You can use the functions provided by os.path for handling pathnames independendly from a platform.

import bpy
import os

filepath = bpy.data.filepath
directory = os.path.dirname(filepath)
print(directory)


To add a file to the basename you could use os.path.join:

newfile_name = os.path.join( directory , "newfile.blend")