Python - How To Set File Path in Python

ID : 530

viewed : 295

Tags : PythonPython Path

vote vote


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.


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.


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')) 



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')) 



  • Related HOW TO?