Search code examples
pythondirectorydircd

Invalid syntax in path when changing directory


In Python, first I check where I am:

import os
os.getcwd()

This gives me %run C:/Users/<name>/Desktop/<script.py> Now I want to change where I am:

os.chdir("C:/Users/<name>/Desktop/")

This gives me

%run C:/Users/<name>/Desktop/<script.py>
  File "C:\Users\<name>\Desktop\<script.py>", line 3
    os.chdir("/C:/Users/<name>/Desktop/")
              ^
SyntaxError: invalid syntax

I have tried variations of this but nothing seems to work.


Solution

  • There are a number of ways that you can do this including:

    Using os.path to join a path and an environment variable:

    os.chdir(os.path.join(os.getenv('userprofile'),'Desktop'))
    

    You could alternatively use either double backslashes (backslash needs to be escaped in Python strings):

    os.chdir('c:\\users\\prosserc\\desktop')
    

    or use a raw string:

    os.chdir(r'c:\users\prosserc\desktop')
    

    I would recommend the first option as it does require a hard coded user name.