Table of Contents
Using pathlib library [Python 3.4+]
Use Path
class’s constructor to convert String to Path in Python. You need to import Path class from pathlib.
1 2 3 4 5 6 |
from pathlib import Path s = "C:/temp/tempFile.txt" path = Path(s) print(path, type(path)) |
Output:
We used the Path()
constructor to convert String to Path. This constructor accepts a string that contains a required path and converts the string to a POSIX path or a Windows path based on your system.
In terms of OS, a path is used to identify a given location in the file system. We can access files and directories using their respective paths in Python.
Usually, paths are represented as strings in Python. However, at times there are issues with this the major one being the misinterpretation of backslash characters as escape sequences and different interpretations of separators in different operating systems.
For Python 3. users and above, a new standard library was added, called pathlib
. The aim of this library was to provide objects that can represent such paths uniformly over operating systems.
The pathlib
library provides two main classes, PurePath
and Concrete Paths (Path
) with the latter being a subclass of the former. The concrete path objects can have access to filesystems and we will convert string to objects of this class.
For example,
To be more specific in conversions, we can use the PosixPath()
and WindowsPath()
constructors as well.
As discussed, this library is only available to Python 3.4 users and above.
Using os.path
module
The os.path
module also provides some features for pathnames.
We can use the os.path.normpath()
function to convert to a standard pathname by removing any redundant separators and normalizing the same. It returns a sting but can accept a path-like object in Python 3.6 and above.
See the code below.
1 2 3 4 5 6 |
import os s = "C:/temp/tempFile.txt" path = os.path.normpath(s) print(path) |
Further reading:
Conclusion
This article discussed how to convert string to path in Python. First, we discussed paths in terms of OS and their use in Python. We highlighted issues related to such pathnames and the use of pathlib
library to introduce uniformity for the same.
The use of the Path
object was demonstrated and we use the constructor for this object to convert string to path in Python. We also discussed the use of the os.path.normpath()
function as well.