How to manipulate pathnames using Python?
In this article, we will learn to manipulate pathnames using Python.
Here are some different examples mentioned below -
Get the main file name from the file path
Get directory name from file path
Connect path components together
Expand the user's home directory
Separate file extension from file path
Algorithm (steps)
Below are the algorithms/steps that need to be followed to perform the required task. -
Use the import keyword to import the os module.
Create a variable to store the input file path.
Use the basename() function of the os module (which returns the base name of the given file path) to get the last component of the input file path (the main file name) and print it out.
Get the main file name from the file path
Example
The following program uses the os.path.basename() function to return the main file name from the input file -
# importing os module import os # input path of the file inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf' # Printing the given input path print("Give Input Path is:",inputFilepath) # getting the last component(main file name )of the input file path print("Base Name of the given path is :",os.path.basename(inputFilepath))
Output
When executed, the above program will generate the following output -
Give Input Path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf Base Name of the given path is: tutorialsPoint.pdf
Get directory name from file path
Use the os.path.dirname() function (which returns the directory name from the given file path) to get the directory/folder of the given input file path by passing it as an argument.
Example
The following program uses the os.path.dirname() function to return the directory name from the input file path -
# importing os module import os # input path of the file inputFilepath = 'C:/Users/cirus/Desktop/tutorialsPoint.pdf' # Printing the given input path print("Give Input Path is:",inputFilepath) # getting the directory/folder path from the input file path using dirname() function print("Directory path of the given path is: ",os.path.dirname(inputFilepath))
Output
When executed, the above program will generate the following output -
Give Input Path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf Directory path of the given path is: C:/Users/cirus/Desktop
Connect path components together
os.path.join() function
Python’s os.path.join() function effectively joins one or more path components. This method joins different path components by placing a directory separator ('/') after each non-empty portion except the last. When the last path component to be added is empty, add a directory separator ("/") at the end.
If the path component represents an absolute path, all previously connected components will be removed and the connection will continue starting from the absolute path component.
Example
The following program uses the os.path.join() function to join the given path components with the base name -
# importing os module import os # input path of the file inputFilepath = 'C:/Users/cirus/Desktop/kohli.pdf' # Printing the given input path print("Give Input Path is:",inputFilepath) # joining the components to the main file name of the input file path print("Joining the given paths to input Path:\n", os.path.join('tutorials', 'python', os.path.basename(inputFilepath)))
Output
When executed, the above program will generate the following output -
Give Input Path is: C:/Users/cirus/Desktop/kohli.pdf Joining the given paths to input Path: tutorials/python/kohli.pdf
Expand the user's home directory
os.path.expanduser() function
Python function os.path.expanduser() Expands the initial path ~ (tilde) or ~user in the specified path to the user's home directory.
grammar
The following is the syntax of this function.
os.path.expanduser(path)
Example
The following program uses the expanduser() function to return the expanded path of the user's home directory -
# importing os module import os # input path of the file inputFilepath = '~/Users/cirus' # Printing the given input path print("Give Input Path is:",inputFilepath) # Expanding the user's home directory print("Expanded Path is:\n",os.path.expanduser(inputFilepath))
Output
When executed, the above program will generate the following output -
Give Input Path is: ~/Users/cirus Expanded Path is: /root/Users/cirus
Separate file extension from file path
os.path.splitext() function - Splits a file pathname into a pair of root and extension. The root here is everything except the file extension.
If the given file path has no extension, the extension will be empty. If a given path has a leading period ("."), the path is ignored.
grammar
The following is the syntax of this function.
os.path.splitext(path)
Use the os.path.splitext() function to split the file path and file extension from the input file path.
Example
The following program uses the os.path.splitext() function to split the main file path and file extension from the input file path -
# importing os module import os # input path of the file inputFilepath ='C:/Users/cirus/Desktop/tutorialsPoint.pdf' # Printing the given input path print("Give Input Path is:",inputFilepath) # splitting the file path and file extension from the input file path # using the splitext() function print("Splitting the given path by extension:\n",os.path.splitext(inputFilepath))
Output
When executed, the above program will generate the following output -
Give Input Path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf Splitting the given path by extension: ('C:/Users/cirus/Desktop/tutorialsPoint', '.pdf')
in conclusion
In this article, we learned how to use OS modules to modify pathnames. From the file path, we learned how to extract the main (base) file name and directory name. We learned how to combine the component name of a path with the path. The user home directory expansion process is discussed. Finally, we found out how to separate the file path from the extension.
The above is the detailed content of How to manipulate pathnames using Python?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Using python in Linux terminal...

Fastapi ...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...
