Set File Path in Python

Siddharth Swami Jan 30, 2023 Sep 12, 2021
  1. Use the \ Character to Specify the File Path in Python
  2. Use the Raw String Literals to Specify the File Path in Python
  3. Use the os.path() Function to Specify the File Path in Python
  4. Use the pathlib.Path() Function to Specify the File Path in Python
Set File Path in Python

Mostly we are provided with the default path variable when we install Python. But sometimes, we have to set these variables manually, or if we want to set a different path, we have to do it manually. To run files saved in our directories, we have to provide the complete path to the editor.

A path usually is a string like C:\Folder. But in Python, the \ character can get interpreted as the escape character.

This tutorial will discuss how to set the path for a file in Python on Windows devices.

Use the \ Character to Specify the File Path in Python

We can use the \\ character in place of a single \ to provide the path in Python.

The syntax for this is shown below.

'C:\\Directory\\File'

Use the Raw String Literals to Specify the File Path in Python

We can use raw string literals to provide paths for the files as a raw string will treat these backslashes as a literal character.

To make a raw string, we have to write the r character before the quotes for the string.

The syntax for using raw string literals is shown below.

r'C:\Directory'

Use the os.path() Function to Specify the File Path in Python

We can also use the path() function of the os module for setting up the path. The advantage of using the path() function is that we do not specify the file’s complete path. We have to provide the directory name and the file name.

This method will itself select the correct configuration for the OS you are using on your device. We have to use the join() function to combine the directory and filename.

For example,

import os
print(os.path.join('C:',os.sep, 'Users'))

Output:

C:\Users

In the above example, the os.sep specifies the default OS separator.

Use the pathlib.Path() Function to Specify the File Path in Python

In Python 3.4 and above, we can use the Path() function from the pathlib module to specify the file paths in Python. Its use is similar to the os.path() function.

See the code below.

from pathlib import Path
print(Path('C:', '/', 'Users'))

Output:

C:\Users

Related Article - Python Path