How to Convert String to Path in Python

In Python, you often deal with file or folder paths, especially when you’re reading from or writing to files.

Instead of treating these paths as plain strings, you can convert them into Path objects using Python’s built-in tools. This makes it easier to work with paths, like joining folders, checking if a file exists, or handling different operating systems.

In this tutorial, I will walk you through some simple ways to convert a string to a path in Python.

Convert String to Path in Python

Let me explain how to convert string to path in Python.

Read Convert Int to Bytes in Python

Method 1: Use pathlib.Path()

Python pathlib.Path() function lets you convert a string that represents a file or folder location into a special Path object that makes working with files and directories much easier.

from pathlib import Path

# A string representing a file path
file_path_string = "C:/Users/Documents/my_file.txt"

# Convert the string to a Path object
file_path = Path(file_path_string)

# Now you can use special Path methods
print(f"File name: {file_path.name}")
print(f"File extension: {file_path.suffix}")
print(f"Parent directory: {file_path.parent}")

Output:

File name: my_file.txt
File extension: .txt
Parent directory: C:/Users/Documents

I executed the above example code and added the screenshot below.

Convert String to Path in Python

Using pathlib.Path() is the modern, recommended way to work with files and folders in Python, replacing older methods like the os.path module functions.

Check out How to Get the Length of a String in Python?

Method 2: Use the os.path module

The os.path module is the best way to work with file paths in Python. It provides functions that let you manipulate file path strings in a way that works across different operating systems.

import os.path

# A string representing a file path
file_path_string = "C:/Users/Documents/my_file.txt"

# Now we can use os.path functions to work with this path
file_name = os.path.basename(file_path_string)
directory = os.path.dirname(file_path_string)
file_extension = os.path.splitext(file_path_string)[1]

# Print the results
print(f"File name: {file_name}")
print(f"Directory: {directory}")
print(f"File extension: {file_extension}")

Output:

File name: my_file.txt
Directory: C:/Users/Documents
File extension: .txt

I executed the above example code and added the screenshot below.

Python String to Path

Unlike pathlib, which creates Path objects, os.path works directly with strings. It provides functions to: extract parts of paths, combine paths, normalize paths, and check file properties.

Read How to Check if a String is Empty in Python?

Method 3: Use Path().resolve() for Absolute Paths

Python Path().resolve() method takes a path (which might be relative or contain shortcuts) and converts it to a complete, absolute path with all references like .. or . resolved.

from pathlib import Path

# A string representing a relative path
relative_path = "documents/../downloads/sample.txt"

# Convert to a Path object and resolve to absolute path
absolute_path = Path(relative_path).resolve()

# Print both paths to see the difference
print(f"Original relative path: {relative_path}")
print(f"Resolved absolute path: {absolute_path}")

Output:

Original relative path: documents/../downloads/sample.txt
Resolved absolute path: C:\Users\YourUsername\downloads\sample.txt

I executed the above example code and added the screenshot below.

How to Convert String to Path in Python

Using resolve() is helpful when you need to compare paths that might be written differently but point to the same location.

Check out How to Reverse a String in Python?

Method 4: Use Path().expanduser() for User Home Directories

Python Path().expanduser() method is a helpful tool that converts path strings containing the tilde character (~) into complete paths that point to the user’s home directory.

from pathlib import Path

# A string representing a path with ~ (tilde) for user's home directory
home_path_string = "~/Documents/notes.txt"

# Convert to a Path object and expand the user home reference
expanded_path = Path(home_path_string).expanduser()

# Print both versions
print(f"Original path with tilde: {home_path_string}")
print(f"Expanded path: {expanded_path}")

Output:

Original path with tilde: ~/Documents/notes.txt
Expanded path: /Users/YourUsername/Documents/notes.txt   (on Mac/Linux)

The expanduser() method makes it much easier to create software that stores data in the proper locations on any user’s computer.

Read How to Compare Strings in Python?

Handle Absolute and Relative Paths in Python

When converting strings to paths in Python, it’s important to understand the difference between absolute and relative paths:

  • Absolute Path: Points to the exact location in your file system, starting from the root (like C:/Users/YourName/Documents/file.txt on Windows).
  • Relative Path: Refers to a location relative to the current working directory (like data/report.csv).

Python’s pathlib module helps you easily handle both types.

from pathlib import Path

# Relative path (assumes there's a folder named 'data' in your current directory)
relative_path = Path("data/report.csv")
print("Is it absolute?", relative_path.is_absolute())
print("Absolute path:", relative_path.resolve())

# Absolute path
absolute_path = Path("/home/user/data/report.csv")  # Change for your OS
print("Is it absolute?", absolute_path.is_absolute())

Using pathlib, you can smoothly manage both absolute and relative paths. This ensures your program works correctly across different systems and directories, especially when reading or writing files.

Check out How to Split a String into Equal Parts in Python?

Example: Load a File from User Input

Imagine you’re building a Python script that reads a file, and the user provides the file path as a string maybe through the command line or a GUI text input.

from pathlib import Path

# Simulate user input (a string path)
user_input = "C:/Users/Alice/Documents/report.txt"

# Convert the string to a Path object
file_path = Path(user_input)

# Check if the file exists
if file_path.exists():
    print("File found:", file_path.name)
else:
    print("File does not exist.")

In many apps or scripts, users enter file paths as strings. Instead of manually parsing the path, pathlib.Path gives you useful tools to validate paths, create new directories, etc.

Conclusion

In this tutorial, I have explained how to convert string to path in Python. I discussed some methods to achieve this task such as using pathlib.Path() , using the os.path module, using Path().resolve() for absolute path, and using Path().expanduser() for user home directories. I also covered how to handle absolute and relative paths in Python and a real-world example.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.