1
$\begingroup$

I'm trying to get the path to my addon on the cpmputer with this command:

path = os.getenv('APPDATA') + "\Blender Foundation\Blender\2.91\scripts\addons\Mold_Generator_Addon"

But the text \2 is interpreted as \x07 in Blender console (and as x02 in this browser)

'C:\\Users\\pqj\\AppData\\Roaming\\Blender Foundation\\Blender\x02.91\\scripts\x07ddons\\Mold_Generator_Addon'

Is there a way to force python to write \2?

$\endgroup$
3
  • 1
    $\begingroup$ \ is an escape character in python. If you don't want \ to be escaped, add a r for "raw" before the first quotation marks of the string $\endgroup$
    – Gorgious
    Feb 13 at 11:25
  • $\begingroup$ medium.com/@ageitgey/… $\endgroup$
    – batFINGER
    Feb 13 at 13:27
  • 1
    $\begingroup$ Voted to close: Generic (and common) python error. See stackoverflow.com/questions/25735930/… Better be consistent: Have closed similar questions before citing same reason. $\endgroup$
    – batFINGER
    Feb 14 at 14:31
2
$\begingroup$
  1. \2 is interpreted as an escape sequence started by a backslash (like \n is a newline). Use a raw string literal, r"\Blender Foundation\Blender\2.91\scripts\addons\Mold_Generator_Addon", if you want a string where backslashes are interpreted literally.
  2. But you should use os.path.join (or pathlib) to make paths anyway. os.path.join("Blender Foundation", "Blender", "2.91", "scripts", "addons", "Mold_Generator_Addon")
  3. But you shouldn't be hardcoding the path anyway. You can get the path to the directory containing the current .py file with os.path.dirname(os.path.abspath(__file__)). This works no matter where it is installed and no matter the Blender version.
$\endgroup$
1
  • $\begingroup$ Perfect. An even better answer than my question merited! Well done, sir. $\endgroup$
    – DrDress
    Feb 13 at 12:15

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