Confirm with pathlib.Path.is_dir()
In the previous step, you used os.path.isdir()
to check if a path is a directory. Now, let's explore another way to achieve the same result using the pathlib
module, which provides an object-oriented approach to file system paths.
The pathlib
module offers a Path
class that represents file system paths. This class has several methods for interacting with files and directories, including the is_dir()
method, which checks if a path is a directory.
To use pathlib
, you first need to import the Path
class from the pathlib
module. Then, you can create a Path
object representing the path you want to check. Finally, you can call the is_dir()
method on the Path
object to determine if it's a directory.
Open the check_type.py
file in the WebIDE's code editor and modify its content to the following:
from pathlib import Path
directory_path = Path("my_directory")
file_path = Path("my_file.txt")
nonexistent_path = Path("nonexistent_directory")
if directory_path.is_dir():
print(f"{directory_path} is a directory")
else:
print(f"{directory_path} is not a directory")
if file_path.is_dir():
print(f"{file_path} is a directory")
else:
print(f"{file_path} is not a directory")
if nonexistent_path.is_dir():
print(f"{nonexistent_path} is a directory")
else:
print(f"{nonexistent_path} is not a directory")
In this script, we are creating Path
objects for my_directory
, my_file.txt
, and nonexistent_directory
. Then, we are using the is_dir()
method to check if each path is a directory.
Save the check_type.py
file.
Now, run the script from the terminal:
python check_type.py
You should see the following output:
my_directory is a directory
my_file.txt is not a directory
nonexistent_directory is not a directory
As you can see, the output is the same as in the previous step when using os.path.isdir()
. The pathlib.Path.is_dir()
method provides an alternative, object-oriented way to check if a path is a directory.
Using pathlib
can make your code more readable and easier to maintain, especially when dealing with complex file system operations.