Python get dir name

Get Directory From Path in Python

Get Directory From Path in Python

  1. Differences in File Path in Various OS
  2. Use os.path.basename to Get Filename From the File Path in Python
  3. Use os.path.splittext to Get Filename From the File Path in Python
  4. Use os.path.dirname to Get Directory Name From the File Path in Python
  5. Use the pathlib Module to Extract Directory Name in Python
  6. Use os.path.abspath to Get Directory Name From the File Path in Python

File paths are unique strings that represent the location of a file in a system or a directory. Sometimes, you may have to retrieve or extract any part or chunk from the file path.

There are several ways you can extract parts from the file path in Python.

Differences in File Path in Various OS

We use the forward-slash / in the Linux directory structure (including MAC), while in Windows, we use the backward slash \ as the separator.

To check which separator your system uses, use the os.sep or os.path.sep . It will return the path separator used by your system.

Use os.path.basename to Get Filename From the File Path in Python

The first and the easiest way to extract part of the file path in Python is to use the os.path.basename() function.

This function returns the filename from the file path along with its extension. Plus, it works for all the Python versions.

import os fpath='c:\Project\input.txt' os.path.basename(fpath) 

Use os.path.basename to Get Filename from the File Path in Python

Use os.path.splittext to Get Filename From the File Path in Python

If you want to extract just the filename from the file path and not its extension, you will use the os.path.splittext() function. This function will only return the filename.

Furthermore, you will add an index 0 with this function to get the desired output. The splittext() function splits the file path into an array. Hence, index 0 represents the filename, and index 1 represents its extension.

import os fpath='c:\Project\input.txt' fname=os.path.splitext(fpath)[0] 

Use os.path.splittext to Get Filename from the File Path in Python

Use os.path.dirname to Get Directory Name From the File Path in Python

The function os.path.dirname() is used to extract the directory name from the path. This function will return the directory name as the string on the Python console.

import os fpath='c:\Project\input.txt' dirname = os.path.dirname(filepath) print(dirname) 

Use os.path.dirname to Get Directory Name from the File Path in Python

This function returns the complete path to the parent directory.

Читайте также:  Java шестнадцатеричный код символа

Use the pathlib Module to Extract Directory Name in Python

Another way to get the directory from the file path is to use the pathlib module. This is specifically available in Python versions 3.4+.

The function takes an argument, the file path, and can return various outputs depending on the item fetched. Let’s import the file along with its path first.

from pathlib import Path p = Path('C:\\Program Files\\Internet Explorer\\iexplore.exe') 

To check the parent directories, execute the following code:

Use the pathlib Module to Extract Directory Name in Python

To fetch the directory and filename as parts, use the part function of the path module. For example:

You will get something like this.

Use the pathlib Module to Extract Directory Name in Python

Use os.path.abspath to Get Directory Name From the File Path in Python

The OS module also offers the functionality to extract a directory from the file path.

This os.path.abspath method takes two different arguments: backslash and dot character. The backslash character returns the root directory, and the dot returns the current directory.

import os directory = os.path.abspath('\\') print(directory) 

Use os.path.abspath to Get Directory Name from the File Path in Python

Here is the code to get the absolute path:

directory = os.path.abspath('.') print(directory) 

This tutorial looked at several functions and modules to split the file path in Python. We have also learned how to extract a name or directory from the file path in Python using OS and Path modules.

Related Article — Python Directory

Related Article — Python Path

Copyright © 2023. All right reserved

Источник

How to get current directory name in Python

In this Python tutorial, I will explain to you, how to get current directory name in Python. By using the Python os module, we will see, how to get current folder name in Python.

Python os module

Before we start, it is essential to understand the ‘os’ module. Python’s os module provides functions to interact with the operating system. This module comes in handy when we want to work with files and directories. One of the common tasks we can do with this module is to get the current directory name.

Get Current Directory in Python Using os.getcwd()

The getcwd() function of the os module returns the current working directory in Python. Here’s how we can use it to get the current folder in Python.

import os current_directory = os.getcwd() print(current_directory)

When you run this code, it will print the full path of your current working directory.

Читайте также:  Python date прибавить день

How to get current directory name in Python

To get just the name of the current directory (and not the full path) or the folder name, we can use the os.path.basename() function. Here’s how we can use it:

import os current_directory = os.getcwd() directory_name = os.path.basename(current_directory) print(directory_name)

This code will print the name of the current directory in Python, without the full path. Or this is how to get the folder name in Python.

How to get current directory name in Python example

Get Directory Name Using os.path.dirname()

Another function from the os module that we can use to get the directory name is os.path.dirname() . The dirname() function returns the directory component of a pathname. However, in most cases, if we want to get the current directory, we still have to use it in conjunction with os.getcwd() :

import os current_directory = os.getcwd() print(os.path.dirname(current_directory))

This code will print the directory that contains the current directory, not the current directory itself.

Get current directory name in Python

To get just the name of the current directory (and not the full path), we can use the os.path.basename() function in conjunction with os.path.dirname() :

import os current_directory = os.getcwd() directory_name = os.path.basename(os.path.dirname(current_directory)) print(directory_name)

Get current directory name in Python example

get the current directory name in Python using pathlib

Pathlib is a module in Python used for object-oriented filesystem paths. It was designed to be simple to use and to represent filesystem paths with semantics appropriate for different operating systems. Here’s how to get the current directory using pathlib in Python:

from pathlib import Path # Get current directory current_directory = Path.cwd() print(current_directory)

get the current directory name in Python using pathlib

Just like with the os module, this will print the full path of the current directory. To get just the name of the current directory, we can use the .name attribute:

from pathlib import Path # Get current directory current_directory = Path.cwd() # Get current directory name directory_name = current_directory.name print(directory_name)

get the current directory name in Python using pathlib example

Conclusion

In this Python tutorial, We’ve looked at different methods to get the current directory in Python, using both the os and pathlib modules.

Remember, os.getcwd() and Path.cwd() give you the current working directory as a full path in Python. If you want only the name of the current directory, you can use os.path.basename(os.getcwd()) or Path.cwd().name .

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Как получить текущее имя каталога в Python

В этом уроке по Python я объясню вам, как получить текущее имя каталога в Python. Используя модуль ОС Python, мы увидим, как получить текущее имя папки в Python.

Читайте также:  Monitor net ru forum topic285281 0 html

Модуль ОС Python

Прежде чем мы начнем, важно понять модуль ОС. питона os Модуль предоставляет функции для взаимодействия с операционной системой. Этот модуль пригодится, когда мы хотим работать с файлами и каталогами. Одна из общих задач, которые мы можем выполнить с помощью этого модуля, — получить имя текущего каталога.

Получить текущий каталог в Python с помощью os.getcwd()

getcwd() Функция модуля os возвращает текущий рабочий каталог в Python. Вот как мы можем использовать его для получения текущей папки в Python.

import os current_directory = os.getcwd() print(current_directory)

Когда вы запустите этот код, он напечатает полный путь к вашему текущему рабочему каталогу.

Чтобы получить только имя текущего каталога (а не полный путь) или имя папки, мы можем использовать функцию os.path.basename() функция. Вот как мы можем его использовать:

import os current_directory = os.getcwd() directory_name = os.path.basename(current_directory) print(directory_name)

Этот код напечатает имя текущего каталога в Python без полного пути.

Получить имя каталога с помощью os.path.dirname()

Еще одна функция из os модуль, который мы можем использовать для получения имени каталога os.path.dirname() . dirname() Функция возвращает компонент каталога пути. Однако в большинстве случаев, если мы хотим получить текущий каталог, нам все равно приходится использовать его вместе с os.getcwd() :

import os current_directory = os.getcwd() print(os.path.dirname(current_directory))

Этот код напечатает каталог, содержащий текущий каталог, а не сам текущий каталог.

Чтобы получить только имя текущего каталога (а не полный путь), мы можем использовать os.path.basename() функционировать в сочетании с os.path.dirname() :

import os current_directory = os.getcwd() directory_name = os.path.basename(os.path.dirname(current_directory)) print(directory_name)

получить текущее имя каталога в Python, используя pathlib

Pathlib это модуль в Python, используемый для объектно-ориентированных путей файловой системы. Он был разработан, чтобы быть простым в использовании и представлять пути файловой системы с семантикой, подходящей для различных операционных систем. Вот как получить текущий каталог с помощью pathlib в Python:

from pathlib import Path # Get current directory current_directory = Path.cwd() print(current_directory)

Так же, как с os модуль, это напечатает полный путь к текущему каталогу. Чтобы получить только имя текущего каталога, мы можем использовать .name атрибут:

from pathlib import Path # Get current directory current_directory = Path.cwd() # Get current directory name directory_name = current_directory.name print(directory_name)

Заключение

В этом руководстве по Python мы рассмотрели различные методы получения текущего каталога в Python, используя как os и pathlib модули.

Помнить, os.getcwd() и Path.cwd() дать вам текущий рабочий каталог как полный путь в Python. Если вам нужно только имя текущего каталога, вы можете использовать os.path.basename(os.getcwd()) или Path.cwd().name .

Вам также может понравиться:

Я Биджай Кумар, Microsoft MVP в SharePoint. Помимо SharePoint, последние 5 лет я начал работать над Python, машинным обучением и искусственным интеллектом. За это время я приобрел опыт работы с различными библиотеками Python, такими как Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn и т. д. для различных клиентов в США, Канаде, Великобритании, Австралии, Новая Зеландия и т. д. Проверьте мой профиль.

Источник

Оцените статью