Take the 2-minute tour ×
Blender Stack Exchange is a question and answer site for people who use Blender to create 3D graphics, animations, or games. It's 100% free, no registration required.

What's the best way to get the full directory of the current Blender file in Python? It should be cross-platform.

share|improve this question
    
    
@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 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 7 at 14:01
add comment

2 Answers

up vote 5 down vote accepted

You could also use 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 MS Windows, with backslash escaped
  • bpy.path.abspath(r"//my\file.txt") on MS Windows, using python raw string
  • bpy.path.abspath("//../file.txt") - to go back a directory.

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

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.

share|improve this answer
    
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 at 16:51
add comment

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")
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.