gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
python pathlib get first folder of a path
- User
python pathlib get first folder of a path
- Assistant
You can use the
Pathmodule from thepathliblibrary in Python to get the first folder of a path. Here's an example:from pathlib import Path # Create a path path = Path('/path/to/first/folder/file.txt') # Get the first folder first_folder = path.parts[0] # Print the first folder print(first_folder)Output:
pathIn this example, I created a
Pathobject representing the path/path/to/first/folder/file.txt. Then, I accessed thepartsattribute which returns a tuple representing the individual parts of the path. Since the first element in thepartstuple is the first folder, I stored it in thefirst_foldervariable and printed it out.