What's the best way to get the full directory of the current Blender file in Python?
It should be cross-platform.
What's the best way to get the full directory of the current Blender file in Python?
It should be cross-platform.
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 escapedbpy.path.abspath(r"//my\file.txt") on Windows, using python raw stringbpy.path.abspath("//../file.txt") to go back a directoryThis 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.
\ 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 07 '14 at 16:51
os.path.sep.
– Anson Savage
Jul 21 '22 at 21:02
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")
/and\\. Or at least useos.path.septo 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 07 '14 at 14:01