"pathlib.Path" - Path for Both Linux and Windows

This section describes the 'Path' class which represents a concrete path for Windows or Unix/Linux systems.

What Is "pathlib.Path" Class? "pathlib.Path" is a class representing concrete path for Windows or Unix/Linux systems.

Main features of "pathlib.Path" are:

1. Automatically detects operating system type and wraps WindowsPath or PosixPath for you. For example:

>>> from pathlib import Path

# A PosixPath object for "/Users/Herong" on Unix/Linux
>>> p = Path('/Users/Herong')
>>> p
PosixPath('/Users/Herong')
>>> str(p)
'/Users/Herong'

# A WindowsPath object for "\Users\Herong" on Windows
>>> p = Path('/Users/Herong')
>>> p
PosixPath('/Users/Herong')
>>> str(p)
'\\Users\\Herong'

Note that Python display "\" as an escape sequence of "\\" on the screen.

2. Uses "/" as the generic path delimiter for both Windows and Unix/Linux systems. See above example.

3. Supports the "/" operator to join sub directory and file names for creating new path objects. For example:

# A PosixPath object for "/Users/Herong" on Unix/Linux
>>> p = Path('.') / 'src' / 'hello.py'
>>> str(p)
'src/hello.py'

# A WindowsPath object for "\Users\Herong" on Windows
>>> p = Path('.') / 'src' / 'hello.py'
>>> str(p)
'src\\hello.py'

4. Automatically detects absolute and relative paths and assigns "/" as the root for absolute paths. For example:

>>> Path('tmp/hello.py').is_absolute()
False
>>> Path('tmp/hello.py').root
''

>>> Path('/tmp/hello.py').is_absolute()
True
>>> Path('/tmp/hello.py').root
'/'

4. Offers a number of nice properties.

5. Offers a number of methods to manage path objects.

6. Offers a number of methods to read and write file contents. See next tutorial for more details.

Table of Contents

 About This Book

 Running Python Code Online

 Python on macOS Computers

 Python on Linux Computers

 Built-in Data Types

 Variables, Operations and Expressions

 Statements - Execution Units

 Function Statement and Function Call

 Iterators, Generators and List Comprehensions

 Classes and Instances

 Modules and Module Files

 Packages and Package Directories

 "sys" and "os" Modules

"pathlib" - Object-Oriented Filesystem Paths

 What Is "pathlib" Module

"pathlib.Path" - Path for Both Linux and Windows

 "pathlib.Path" - Read and Write Operations

 "pip" - Package Installer for Python

 SciPy.org - Python Libraries for Science

 pandas - Data Analysis and Manipulation

 Anaconda - Python Environment Manager

 Jupyter Notebook and JupyterLab

 References

 Full Version in PDF/EPUB