Python Forum

Full Version: Changing Directory; Syntax Error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am studying now about importing modules. Of course I started with the basics. I am running the latest version of Python on Windows 8.1.
Here is my sample code written on the shell:
import os
os.chdir("C:\Users\User\Desktop\Projects")
However, I always get this error message:
Error:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
Any suggestions of resolving this?
Backslashes in string indicate special characters. \U indicates a unicode character. There are many possible solutions for this:
  • Put an r before the string (r'String\With\Backslashes'). That creates a raw string literal, that treats backslashes as plain characters.
  • Double backslash in a normal string is treated as a single backslash ('String\\With\\Backslashes').
  • Use Unix-style forward slashes. Python will translate it to the relevant file system syntax and it won't cause problems with special characters.