How to add a string to a path in Python using pathlib?

In this blog post, we’ll explore how to add a string to a path using pathlib, a library introduced in Python 3.4.

The key benefit of the pathlib module is that it brings together the capabilities of many other Python modules like os.path, os, and glob into one object, making file system interactions way easier.

Concatenate string to Python path object

In our example, we will organize employee data into files stored in department-specific folders.

Here is the Python code that you can use:

# import the Path module - will work from Python 3.4 and onwards

from pathlib import Path

# Define directory for employee files

base_dir = Path('/path/to/employee_data')

Next we will define employee information as a Python dictionay of strings and add those to the folder path:

employees = {'name': 'Jorge_Cortez', 'department': 'IT'}

# Concatenate department string to path

department_path = base_dir / employees['department']

# Create a text file for each employee

file_path = department_path / (employees['name'] + '.txt')

# output the file path

print(file_path)

Important Note: The code above implements automatic handling of different operating systems name conventions. Pathlib abstracts the complexity of different OS path conventions. Hence, this code will work on macOS, Linux and Windows.

FAQ

Can I convert a pathlib Path object to a Python string?

Yes, you can use the str() function.
Here is a simple example:

str(Path(‘/employees/IT’)).

How to rename a file using the pathlib?

Yes, you can use the rename method of the Path object.For example, let’s rename a simple Excel spreadsheet:

Path(‘my_old_name.xlsx’).rename(‘my_new_name.xlsx’).

Is it possible to combine multiple paths using pathlib?

Yes, use the ‘/’ operator to join pathlib paths.
For example:

Path(‘/employees/IT’) / ’employee_subfolder’.