How to convert a string to a path object in Python?

String to path object with Pathlib

Assume that we have the following string that represents a file location in a Windows operating system.

path_str = 'C:\WorkDir\logfile.txt'

We can check the object type of our string using type:


# this will return str or <class 'str'>

Starting Python 3.4 we are able to use the pathlib library, which is part of the standard library, to easily cast a string and transform it to a path object.

# import pathlib into your dev environment
from pathlib import Path

f_path = Path(path_str)

As i am writing this on Windows laptop, this will return:


Pathlib path to string

What if we would like to go the other way around, and convert our path object to a string? You can easily accomplish that using the str function.


Format string to path with os

In the next example, we will construct a path to a file using the os module. We will define string corresponding to the directory path, the file name and the file extension. We’ll then join them using os.path.join function. If you are on Python 3.4 and above, you can use the Path function to derive a path object as we have shown before.

import os, from pathlib import Path

dir_str = 'C:\WorkDir\''
file_name = 'logfile'
file_ext = '.txt'
Path( os.path.join(dir_str, file_name, file_ext)

Get a directory from a file path

If you need to truncate the path to a directory from a file path you can use the os.split() method:

import os
f_path  = r"C:\WorkDir\file.txt"
filedir, filename = os.path.split(f_path)

Follow-up learning

How to use Python to add rows to a text file?