Python Tutorial- Absolute and Relative Paths

Python Exercise Lists

Before introducing absolute and relative paths, let's understand what the current working directory is.

What is the Current Working Directory in Python?

Every program running on your computer has a "current working directory" (or cwd). All file names or paths that do not start from the root folder are assumed to be in the current working directory.

Note that although the folder is the updated name of the directory, the current working directory (or current directory) is a standard term and there is no such thing as the current working folder.

import os

The output is:


It can be seen that the original current working path is 'C:\\Windows\\Python' (that is, the desktop). Through the os.chdir() function, it is changed to' C:\\Windows\\System32 '.

It should be noted that if the working directory modified by os.chdir () does not exist, the Python interpreter will report an error, for example:


The output is:

FileNotFoundError         Traceback (most recent call last)
[ipython-input-14-c95b0db87686] in [module>]
----> 1 os.chdir('C:\\error')

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\error'

After understanding the specific meaning of the current working directory, the following introduces the meaning and usage of absolute and relative paths.

What are absolute and relative paths in Python?

There are two ways to specify the path of a file:

  • Absolute path: Always start from the root folder. The drive letter (C :, D :) is used as the root folder in the Windows system, and / is used as the root folder in the OS X or Linux system.
  • Relative path: refers to the location of the file relative to the current working directory. For example, the current working directory is "C:\Windows\System32". If the file demo.txt is located in this System32 folder, the relative path of demo.txt is represented as ".\Demo.txt" (where .\ Means Directory).

When using a relative path to indicate the location of a file, in addition to often using .\ to indicate the current directory .\ is also used to indicate the parent directory of the current directory.

Python Handles Absolute and Relative Paths in Python

The Python os.path module provides functions that can convert between absolute and relative paths, and check whether a given path is an absolute path, such as:

  • Calling os.path.abspath (path) returns a string of the absolute path of the path parameter, which is a convenient way to convert a relative path to an absolute path;
  • Calling os.path.isabs (path). If the parameter is an absolute path, return True. If the parameter is a relative path, return False;
  • Calling os.path.relpath (path, start) returns a string of relative paths from the start path to the path. If start is not provided, the current working directory is used as the start path;
  • Calling os.path.dirname (path) returns a string containing everything before the last slash in the path parameter;
  • calling os.path.basename (path) returns a string containing the last in the path parameter everything after a slash.

Try the functions mentioned above in an interactive environment:

os.path.relpath('C:\\Windows', 'C:\\')
os.path.relpath('C:\\Windows', 'C:\\spam\\eggs')
path = 'C:\\Windows\\System32\\calc.exe'

The output is:


Note that because the reader's system files and folders may be different from mine, the reader does not have to follow the examples in this section completely and make appropriate adjustments to the code in this section according to their system environment.

In addition, if you need both the directory name and the base name of a path, you can call os.path.split() to get a tuple of these two strings, for example:

path = "C:\Windows\System32\AdvancedInstallers\cmiv2.dll"

The output is:

('C:\\Windows\\System32\\AdvancedInstallers', 'cmiv2.dll')

Note that you can call os.path.dirname() and os.path.basename() and put their return values in a tuple to get the same tuple. But using os.path.split() is definitely a good shortcut.

At the same time, if the provided path does not exist, many Python functions will crash and report an error, but fortunately the os.path module provides the following functions to detect whether a given path exists and whether it is a file or a folder:

  • If the file or folder pointed to by the path parameter exists, calling os.path.exists(path) returns True, otherwise returns False.
  • If the path parameter is present and it is a file, calling os.path.isfile(path) will return True, otherwise it will return False.
  • If the path parameter is present and it is a folder, calling os.path.isdir(path) will return True, otherwise it will return False.

Here are the results of trying these functions in an interactive environment:


The output is:



More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression

More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises