Pular para o conteúdo

Como usar o pathlib path facilmente?

[

Python’s pathlib Module: Taming the File System

Working with files and interacting with the file system are common tasks for Python developers. Some cases may involve only reading or writing files, but sometimes more complex tasks are at hand. Maybe you need to list all files of a given type in a directory, find the parent directory of a given file, or create a unique filename that doesn’t already exist. That’s where pathlib comes in.

The pathlib module is part of Python’s standard library, and it helps you deal with all those challenges. It gathers the necessary functionality in one place and makes it available through methods and properties on a convenient Path object.

In this tutorial, you’ll learn how to:

  • Work with file and directory paths in Python.
  • Instantiate a Path object in different ways.
  • Use pathlib to read and write files.
  • Carefully copy, move, and delete files.
  • Manipulate paths and the underlying file system.
  • Pick out components of a path.

You’ll also explore a bunch of code examples in this tutorial, which you can use for your everyday file operations. For example, you’ll dive into counting files, finding the most recently modified file in a directory, and creating unique filenames.

The Problem With Representing Paths as Strings

With Python’s pathlib, you can save yourself some headaches. Its flexible Path class paves the way for intuitive semantics. Before you have a closer look at the class, take a moment to see how Python developers had to deal with paths before pathlib was around.

Traditionally, Python has represented file paths using regular text strings. However, since paths are more than plain strings, important functionality was spread all around the standard library, including in libraries like os, glob, and shutil.

As an example, the following code block moves files into a subfolder:

import glob
import os
import shutil
for file_name in glob.glob("*.txt"):
new_path = os.path.join("archive", file_name)
shutil.move(file_name, new_path)

You need three import statements in order to move all the text files to an archive directory. This approach can quickly become cumbersome and hard to read, especially when dealing with more complex path operations.

Path Instantiation With Python’s pathlib

The first step to start using pathlib is to instantiate a Path object. There are different ways to do this. Let’s explore them:

Using Path Methods

pathlib provides a Path() method that allows you to create a Path object. This method can take multiple arguments, each representing a part of the path. For example, to create a Path object representing the file example.txt in the current directory, you can use the following code:

from pathlib import Path
path = Path("example.txt")

In this case, the argument passed to the Path() method is a string representing the file name. You can also pass multiple arguments to represent a more complex path structure, like directories and subdirectories.

Passing in a String

Another way to create a Path object is by passing in a string representing the path. The Path() method can directly accept a string as its argument. For example:

from pathlib import Path
path = Path("path/to/example.txt")

Here, the string "path/to/example.txt" represents the file example.txt located in the path/to directory.

Joining Paths

One of the advantages of pathlib is the ability to easily join multiple path elements together. This is done using the / operator. For example, you can join two paths like this:

from pathlib import Path
directory = Path("path/to")
file_name = Path("example.txt")
path = directory / file_name

In this case, the resulting path object represents the file example.txt located in the path/to directory.

File System Operations With Paths

Once you have a Path object representing a file or directory, you can perform various file system operations on it. pathlib provides methods and properties to help you accomplish these tasks. Let’s explore some of them:

Picking Out Components of a Path

The Path object provides properties that allow you to access different parts of the path. For example, you can use the name property to get the name of the file or directory represented by the Path object:

from pathlib import Path
path = Path("path/to/example.txt")
print(path.name) # Output: example.txt

Similarly, you can use the parent property to get the parent directory of the file or directory:

from pathlib import Path
path = Path("path/to/example.txt")
print(path.parent) # Output: path/to

Reading and Writing Files

pathlib provides methods for reading and writing files. The read_text() method allows you to read the contents of a file as a string:

from pathlib import Path
path = Path("example.txt")
content = path.read_text()
print(content)

To write to a file, you can use the write_text() method:

from pathlib import Path
path = Path("example.txt")
path.write_text("Hello, world!")

Renaming Files

To rename a file, you can use the rename() method of the Path object. Here’s an example:

from pathlib import Path
path = Path("old_name.txt")
path.rename("new_name.txt")

Copying Files

To copy a file, you can use the copy() method. It creates a new file with the same contents as the original file. Here’s an example:

from pathlib import Path
source_path = Path("original_file.txt")
destination_path = Path("copy_file.txt")
source_path.copy(destination_path)

Moving and Deleting Files

To move a file to a different directory or rename it, you can use the replace() method. It takes a new path as its argument. Here’s an example:

from pathlib import Path
source_path = Path("file.txt")
destination_path = Path("new_directory/new_name.txt")
source_path.replace(destination_path)

To delete a file, you can use the unlink() method:

from pathlib import Path
path = Path("file.txt")
path.unlink()

Creating Empty Files

To create an empty file, you can use the touch() method:

from pathlib import Path
path = Path("new_file.txt")
path.touch()

Python pathlib Examples

Now that you have an understanding of the basic concepts of pathlib, let’s explore some practical examples:

Counting Files

You can use pathlib to count the number of files in a directory:

from pathlib import Path
directory = Path("path/to/directory")
file_count = sum(1 for _ in directory.iterdir() if _.is_file())
print(file_count)

This code snippet counts the number of files in the path/to/directory directory and displays the result.

Displaying a Directory Tree

pathlib allows you to create a tree-like representation of a directory and all its subdirectories:

from pathlib import Path
directory = Path("path/to/directory")
for path in directory.glob("**/*"):
depth = len(path.relative_to(directory).parts)
print("-" * depth, path.name)

This code snippet displays a tree-like representation of the path/to/directory directory and all its subdirectories.

Finding the Most Recently Modified File

You can use pathlib to find the most recently modified file in a directory:

from pathlib import Path
directory = Path("path/to/directory")
most_recent_file = max(directory.iterdir(), key=lambda f: f.stat().st_mtime)
print(most_recent_file)

This code snippet finds the most recently modified file in the path/to/directory directory and displays its name.

Creating a Unique Filename

If you need to create a new file with a unique name, you can use pathlib to generate a unique filename:

from pathlib import Path
import uuid
directory = Path("path/to/directory")
file_name = f"file_{uuid.uuid4().hex}.txt"
new_file = directory / file_name
new_file.touch()

This code snippet generates a unique filename using the uuid module and creates a new file with that name in the path/to/directory directory.

Conclusion

In this tutorial, you’ve learned how to use Python’s pathlib module to work with file and directory paths. You’ve seen how to instantiate a Path object, perform file system operations on paths, and manipulate paths and the underlying file system. You’ve also explored several code examples that demonstrate practical use cases of pathlib.

pathlib provides a powerful and intuitive way to work with paths in Python, making it easier to handle file and directory operations in your code. With the knowledge you’ve gained, you’ll be able to tame the file system and efficiently work with files and directories in your Python projects.