Table of Contents
Algorithm (steps)
Get the main file name from the file path
Example
Output
Get directory name from file path
Connect path components together
os.path.join() function
Expand the user's home directory
os.path.expanduser() function
grammar
Separate file extension from file path
in conclusion
Home Backend Development Python Tutorial How to manipulate pathnames using Python?

How to manipulate pathnames using Python?

Sep 15, 2023 pm 07:13 PM
python path operation python path processing python path management

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 -

1

2

3

4

5

6

7

8

9

10

11

# 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))

Copy after login

Output

When executed, the above program will generate the following output -

1

2

Give Input Path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf

Base Name of the given path is:  tutorialsPoint.pdf

Copy after login

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 -

1

2

3

4

5

6

7

8

9

10

# 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))

Copy after login

Output

When executed, the above program will generate the following output -

1

2

Give Input Path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf

Directory path of the given path is:  C:/Users/cirus/Desktop

Copy after login

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 -

1

2

3

4

5

6

7

8

9

10

11

# 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)))

Copy after login

Output

When executed, the above program will generate the following output -

1

2

3

Give Input Path is: C:/Users/cirus/Desktop/kohli.pdf

Joining the given paths to input Path:

 tutorials/python/kohli.pdf

Copy after login

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.

1

os.path.expanduser(path)

Copy after login

Example

The following program uses the expanduser() function to return the expanded path of the user's home directory -

1

2

3

4

5

6

7

8

9

# 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))

Copy after login

Output

When executed, the above program will generate the following output -

1

2

3

Give Input Path is: ~/Users/cirus

Expanded Path is:

 /root/Users/cirus

Copy after login

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.

1

os.path.splitext(path)

Copy after login

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 -

1

2

3

4

5

6

7

8

9

10

# 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))

Copy after login

Output

When executed, the above program will generate the following output -

1

2

3

Give Input Path is: C:/Users/cirus/Desktop/tutorialsPoint.pdf

Splitting the given path by extension:

 ('C:/Users/cirus/Desktop/tutorialsPoint', '.pdf')

Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

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 teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

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 to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

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 avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

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

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

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...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles