How to create a path to a file or directory relative to the current working directory using the path package?

To create a path to a file or directory relative to the current working directory using the path package in Python, you can follow these steps:

  1. Import the Path class from the path package:
from path import Path
  1. Create a Path object with the current working directory using the Path.cwd() method:
current_dir = Path.cwd()
  1. Use the / operator to append the file or directory name to the path:
file_path = current_dir / "file.txt" directory_path = current_dir / "directory"
  1. You can also append multiple subdirectories by calling the / operator multiple times:
subdirectory_path = current_dir / "directory" / "subdirectory"
  1. You can convert the path to a string using the str() function:
print(str(file_path)) print(str(directory_path)) print(str(subdirectory_path))

By following these steps, you will have created a path to a file or directory relative to the current working directory using the path package in Python.