Set File Path in Python

This tutorial will cover ways to manually set the file path in Python to something other than the current working directory.

 

Specify File Path Using the \ Character in Python

The \ (backslash) character is an escape character in regex. To specify directory paths in Python we can use a double backslash (\\) to create a single literal backslash.

 

'C:\\directory\\file.txt'

 

Set File Path Using String Literals in Python

If you put an r character before the file path string Python will interpret all characters inside it as literals, saving the need to escape backslashes.

 

r'C:\directory\file.txt'

 

Set File Path Using os.path() in Python

The os package is a nice way to set file paths in Python because you only need to provide the complete path.

 

MEDIA_ROOT = os.path.join('C:',os.sep, 'static',os.sep, 'images')
C:\static\images