Python [WinError 3] The system cannot find the path specified:

My current working directory is

C:Users18327Desktop

I have the following code:

#Load os module
import os

#this is the abs path of my Temp folder
my_path = "C:/Users/18327/Desktop/New/Temp/"

#my parent folders
start = "C:/Users/18327/Desktop"

relative_path = os.path.relpath(my_path, start)

#relative path is NewTemp
print(relative_path)

#get and print current path of the current machine
current_path = os.getcwd()
print('current path is {}'.format(current_path))

#combine them

temp_path = os.path.join(current_path,
                            relative_path)
print(temp_path)


#set the path to your current medline folder

os.chdir(temp_path)

The first time I ran it I got the desired path I wanted, which is

NewTemp
current path is C:Users18327Desktop
C:Users18327DesktopNewTemp

However, when I ran the code again, I got

NewTemp
current path is C:Users18327DesktopNewTemp
C:Users18327DesktopNewTempNewTemp
*** FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\Users327\Desktop\New\Temp\New\Temp'

How do I modify the code so that each time I run it I get the result

C:Users18327DesktopNewTemp

Answer

This happens since you’re changing the working dir with os.chdir and not changing it back to where it was at the end of your run, while also using relative paths instead of absolute paths.

You could add old_working_dir = os.os.getcwd() at the start of your file and os.chdir(old_working_dir) at the end to return to where you were and have it run again as intended, but that’s a bit hacky for my taste.

A much better solution would be to not use chdir at all, and make your script work with absolute paths instead of relative ones if possible.

Also, check out pathlib for many easier ways to deal with file paths.