Last modified: Mar 23, 2025 By Alexander Williams

Python Pathlib.name Explained

Python's pathlib module is a powerful tool for working with file paths. One of its useful methods is name. This method helps you extract the file name from a path.

In this article, we'll explore how to use pathlib.name effectively. We'll also provide examples to make it easy to understand.

What is pathlib.name?

The name attribute in pathlib returns the final component of a path. This is usually the file name. It works on both files and directories.

For example, if your path is /home/user/file.txt, name will return file.txt.

How to Use pathlib.name

Using pathlib.name is straightforward. First, import the Path class from the pathlib module. Then, create a Path object and access its name attribute.


from pathlib import Path

# Create a Path object
path = Path("/home/user/file.txt")

# Get the file name
file_name = path.name

print(file_name)
    

file.txt
    

In this example, path.name returns file.txt. This is the final component of the path.

Working with Directories

pathlib.name also works with directories. If the path points to a directory, name will return the directory name.


from pathlib import Path

# Create a Path object for a directory
path = Path("/home/user/documents")

# Get the directory name
dir_name = path.name

print(dir_name)
    

documents
    

Here, path.name returns documents, which is the name of the directory.

Combining with Other Methods

You can combine pathlib.name with other methods like with_suffix or with_name for more advanced path manipulations.

For example, you can change the file extension using with_suffix and then get the new file name.


from pathlib import Path

# Create a Path object
path = Path("/home/user/file.txt")

# Change the file extension
new_path = path.with_suffix(".pdf")

# Get the new file name
new_file_name = new_path.name

print(new_file_name)
    

file.pdf
    

In this example, with_suffix changes the file extension to .pdf, and name retrieves the new file name.

Conclusion

The pathlib.name method is a simple yet powerful tool for extracting file names from paths. It works with both files and directories.

By combining it with other pathlib methods, you can perform complex path manipulations with ease. For more details on related methods, check out our guides on Python Pathlib with_suffix() Explained and Python Pathlib with_name() Explained.

Start using pathlib.name in your projects today to simplify your file path handling!