Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 966
turnip Avatar asked Jul 07 '26 11:07

turnip


1 Answers

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.

like image 123
ChrisProsser Avatar answered Jul 10 '26 09:07

ChrisProsser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!