In this tutorial we will learn how to concatenate a file path and a file name using the pathlib library.
Step 1: Import the pathlib library
First off, you should make sure to import the Path module which is part of the pathlib package.
from pathlib import Path
If you try to use the Path module, before importing it first, you will receive the following Nameerror exception:
NameError: name 'Path' is not defined
This tutorial has more explanation about this error and how to solve it. It’s also key to remember that pathlib was introduced in Python 3.4, and doesn’t exist in previous versions.
Step 2: Define your file path, directory and name variables
Next, we will define the required variables:
file_name = "my_text_file.txt"
file_dir = "Examples"
file_path = "C:/Temp/"
Step 3: Concatenate the file path and name with pathlib
Creating a path object is simple, all we need to do is to join the variables specified above:
full_path_to_file = Path(file_path, file_dir, file_name)
We can then get and print the path we created as needed:
WindowsPath('C:/Temp/Examples/my_text_file.txt')
Important Note: As i am writing this tutorial on a Windows system, our program has created a WindowsPath object. Unlike the os library, pathlib is able to render path objects, according to the operating systems you are using: Linux, Unix, macOS and Windows.
Step 4: Create a file object at a specific path (optional)
A final (and optional) step is to create a file if it doesn’t exist in the file path we have constructed in the previous step. Here’s a very simple Python code, that you can enhance to check for additional edge cases.
if full_path_to_file.is_file():
print('File exists.')
else:
full_path_to_file.touch(exist_ok=True)
print('File was created.')