
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to extract a part of the file path (a directory) in Python?
In Python 3.4+ you can use the pathlib module to get the parent directory. For example,
from pathlib import Path print(Path('/home/username').parent) This will give the output: /home
In older versions, you can call the os.path.join on your path and '..'(represents parent directory) and then find its absolute path using os.path.abspath.
For example
import os print(os.path.abspath(os.path.join('/home/username', '..'))) This will give the output: /home
- Related Articles
- How to get full path of current file's directory in Python?
- How to print full path of current file's directory in Python?
- Specify a path for a file or a directory in Java
- Find last Directory or file from a given path
- How to check if a file is a directory or a regular file in Python?
- C# Program to check if a path is a directory or a file
- How to open a file in the same directory as a Python script?
- How to extract part of a URL in MySQL?
- How to get the file name from the file path in Python?
- Get the absolute path for the directory or file in Java
- How to extract file extension using Python?
- How to search a file in a directory in java
- How to extract all the .txt files from a zip file using Python?
- Java Program to get the File object with the absolute path for the directory or file
- How to specify the file path in a tkinter filedialog?

Advertisements