

Python will display an error if you try to change to a directory that does not exist. When we change the current working directory to C:\Windows, project.docx is interpreted as C:\ Windows\project.docx. Here, the current working directory is set to C:\Python34, so the filename project.docx refers to C:\Python34\project.docx. Enter the following into the interactive shell:


You can get the current working directory as a string value with the os.getcwd() function and change it with os.chdir(). Any filenames or paths that do not begin with the root folder are assumed to be under the current working directory. Print(os.path.join('C:\\Users\\asweigart', filename))Įvery program that runs on your computer has a current working directory, or cwd.

For example, the following example joins names from a list of filenames to the end of a folder’s name: These strings will be passed to several of the file-related functions introduced in this chapter. The os.path.join() function is helpful if you need to create strings for filenames. (Notice that the backslashes are doubled because each backslash needs to be escaped by another backslash character.) If I had called this function on OS X or Linux, the string would have been 'usr/bin/spam'. I’m running these interactive shell examples on Windows, so os.path.join('usr', 'bin', 'spam') returned 'usr\\bin\\spam'. If you pass it the string values of individual file and folder names in your path, os.path.join() will return a string with a file path using the correct path separators. If you want your programs to work on all operating systems, you will have to write your Python scripts to handle both cases.įortunately, this is simple to do with the os.path.join() function. OS X and Linux, however, use the forward slash ( /) as their path separator. On Windows, paths are written using backslashes ( \) as the separator between folder names. Backslash on Windows and Forward Slash on OS X and Linux
