38

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

It should be cross-platform.

ideasman42
  • 47,387
  • 10
  • 141
  • 223
Garrett
  • 6,596
  • 6
  • 47
  • 75
  • http://blender.stackexchange.com/questions/2545/quick-way-to-get-current-opened-filename-in-a-script – stacker Feb 07 '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 07 '14 at 11:55
  • 1
    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 07 '14 at 14:01

2 Answers2

40

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.

Gorgious
  • 30,723
  • 2
  • 44
  • 101
ideasman42
  • 47,387
  • 10
  • 141
  • 223
  • 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 07 '14 at 16:51
  • To get the correct separator character, you should use os.path.sep. – Anson Savage Jul 21 '22 at 21:02
22

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")
stacker
  • 38,549
  • 31
  • 141
  • 243