Search code examples
pythonjupyter-notebookcd

Change to a directory with white space...works in .ipynb but not .py?


Trying to convert my Jupyter Notebooks to python scripts so that I can automate them on a daily basis. On Mac.

This works in Notebooks with no problem:

cd '/Volumes/GoogleDrive/My Drive/dailyScripts'

But then when I try to run it as a .py file, there's various issues.

  • First, it rejects the quotes as invalid syntax.
cd '/Volumes/GoogleDrive/My Drive/dailyScripts'
   ^
SyntaxError: invalid syntax
  • So I drop the quotes but then obviously it doesn't like the white space without a backslash.
cd /Volumes/GoogleDrive/My Drive/dailyScripts
                          ^
SyntaxError: invalid syntax
  • So then I added a backslash but now it doesn't like that \ in Python is a line continuation character.
cd /Volumes/GoogleDrive/My\ Drive/dailyScripts
                                              ^
SyntaxError: unexpected character after line continuation character

I've also tried double quotes. Not sure what other options there are. Thanks in advance!


Solution

  • This is because cd is a shell command for a command line interface (e.g. terminal on mac/linux, or Command prompt/Powershell on windows). IPython notebooks are "smart" such that when they see you begin a line with cd ... it will automatically run it through the pseudo-terminal for you.

    Python on its own has no knowledge of cd or other shell programs, instead it bundles all of its interfacing with the operating system inside of the os module in the standard library. So, to change the directory from inside of a python script, you'll need to use the os module and use the chdir function like so:

    import os
    
    os.chdir("/Volumes/GoogleDrive/My Drive/dailyScripts")
    

    Further reading on os.chdir