Python on Mac // Changing Working Directory

3.9k Views Asked by At

I have been instructed to change the working working directory. We were provided a file and instructed to put in the Documents folder if we were using a Mac. I cannot seem to to get it work.

from pathlib import Path
import os
Path.cwd()
print(os.getcwd())
os.chdir('/Users/VClark/Documents/cpt180Stuff')
Path.cwd()
print(os.getcwd())

This is the error I am getting:

/Users/VClark/Desktop/CPT 180
Traceback (most recent call last):
  File "/Users/VClark/Desktop/CPT 180/workWithFiles.py", line 9, in <module>
    os.chdir('Users/VClark/Documents/cpt180Stuff')
FileNotFoundError: [Errno 2] No such file or directory: 'Users/VClark/Documents/cpt180Stuff'
2

There are 2 best solutions below

1
Hussein Esmail On

When you are dealing with directories, you must always have a "/" at the beginning of the file path, and at the end, indicating the last word is also a folder, or else it will be treated as a file. And you can't change directories to a file. /Users/hussein/Documents/ is good, Users/hussein/Documents/ and /Users/hussein/Documents are not.

1
Megsman On

I just found out that in MacOS to use os.chdir() you need to put the directory path in double quotes. Ex. os.chdir("/User/tom").

To change to a directory within the current working directory: os.chdir("directory_name") -- without the slash.