Os getcwd python что это

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
os.getcwd() method tells us the location of current working directory (CWD).
Parameter: No parameter is required.
Return Value: This method returns a string which represents the current working directory.
Python Get Current Directory – Print Working Directory PWD Equivalent

Dionysia Lemonaki

In this article, you will learn how to get the current working directory (another name for folder) in Python, which is the equivalent of using the pwd command.
There are a couple of ways to get the current working directory in Python:
- By using the os module and the os.getcwd() method.
- By using the pathlib module and the Path.cwd() method.
Let’s get started!
How to Get The Current Directory Using the os.getcwd() Method in Python
The os module, which is part of the standard Python library (also known as stdlib), allows you to access and interact with your operating system.
To use the os module in your project, you need to include the following line at the top of your Python file:
Once you have imported the os module, you have access to the os.getcwd() method, which allows you to get the full path of the current working directory.
Let’s look at the following example:
The output is a string that contains the absolute path to the current working directory – in this case, python-project .
To check the data type of the output, use the type() function like so:
Note that the current working directory doesn’t have a trailing forward slash, / .
Keep in mind also that output will vary depending on the directory you are running the Python script from as well as your Operating System.
How to Get The Current Directory Using the Path.cwd() Method in Python
In the previous section, you saw how to use the os module to get the current working directory. However, you can use the pathlib module to achieve the same result.
The pathlib module was introduced in the standard library in Python’s 3.4 version and offers an object-oriented way to work with filesystem paths and handle files.
To use the pathlib module, you first need to import it at the top of your Python file:
Once you have imported the pathlib module, you can use the Path.cwd() class method, which allows you to get the current working directory.
Let’s look at the following example:
As you can see, the output is the same as the output I got when I used the os.getcwd() method. The only difference is the data type of the output:
Conclusion
And there you have it! You now know how to get the full path to the current directory in Python using both the os and pathlib modules.
Примеры использования модуля os в Python

Данный модуль можно применять во многих случаях. В данном разделе мы не рассмотрим каждый из них. Вместо этого, мы рассмотрим, как именно его можно применять, а также ознакомимся с подмодулем, под названием os.path. В частности, мы расскажем о:
- os.name
- os.environ
- os.chdir()
- os.getcwd()
- os.getenv()
- os.putenv()
- os.mkdir()
- os.makedirs()
- os.remove()
- os.rename()
- os.rmdir()
- os.startfile()
- os.walk()
- os.path
Это может выглядеть как большой объем материала, но есть еще минимум десяток других задач, которые модуль os может выполнять. Так что данный раздел можно назвать кратким экскурсом. Для использования любого из методов, упомянутых в данном разделе, вам нужно импортировать модуль os, вот так:
os.name
Модуль os обладает как вызываемыми функциями, так и обычными значениями. В случае с os.name, речь идет только о значениях. При доступе к os.name, вы получите информацию о том, с какой платформой вы работаете. Вам откроются следующие значения: ‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’, ‘riscos’. Давайте посмотрим на то, что выйдет, если запустить его на Windows 7:
Это говорит нам о том, что наш экземпляр Пайтон работает в окне Windows. Как мы об этом узнали? Майкрософт начали называть свою операционную систему NT много лет назад. Например, Windows 7 также носит имя Windows NT 6.1.
os.environ, os.getenv() и os.putenv()
Значение os.environ известно как объект мэппинга (сопоставления), который работает со словарем переменных пользовательской среды. Возможно вы не знали, но каждый раз, когда вы пользуетесь своим компьютером, некоторые переменные среды уже установлены.
Это дает вам полезную информацию, такую как количество процессоров, тип ОЗУ, имя компьютера, и так далее. Посмотрим, что мы сможем узнать о нашем компьютере:
Ваши данные будут отличаться от моих, так как конфигурация компьютера у всех немного отличается, однако вы определенно увидите большое количество совпадений. Как вы могли заметить, это вернуло словарь. Это значит, что вы можете получить доступ к значениям среды, пользуясь обычными словарными методами. Например:
Вы также можете использовать функцию os.getenv для доступа к этой переменной:
Полезность использования os.getenv() вместо словаря os.environ заключается в том, что если вы находитесь в положении, когда вам нужно получить доступ к переменной среды, которая не существует, функция getenv попросту ничего не сделает. Если вы попытаетесь сделать то же самое, пользуясь os.environ, вы получите уведомление об ошибке. Давайте попробуем на примере:
Результат выполнения данного скрипта:
Есть вопросы по Python?
На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!
Telegram Чат & Канал
Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!
Паблик VK
Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!
os.chdir() и os.getcwd()
Функция os.chdir позволяет нам вносить изменения в каталоге, который мы в данный момент используем в сессии. Если вам нужно знать, какой путь вы в данный момент используете, для этой нужно вызвать os.getcwd(). Попробуем воспользоваться обоими модулями:
Указанный код демонстрирует нам, что мы открыли директорию по умолчанию в Пайтоне, после запуска данного кода в IDLE. После этого мы изменили папки, при помощи os.chdir(). Наконец, мы вызывали os.getcwd() еще раз, чтобы убедиться, что все изменения были выполнены правильно.
os.mkdir() и os.makedirs()
Как вы могли догадаться, эти два метода используются для создания папок. Первая, os.mkdir(), позволяет создать одну папку. Попробуем:
Первая строка кода создает папку под названием test в определенном каталоге. Вы можете использовать эти модули в предыдущем разделе, чтобы узнать, где именно вы запустили свой код, на случай, если вы забыли. Во втором примере мы назначили путь к переменной, затем к os.mkdir(). Это позволяет вам создать папку в любой точке вашей системы, где есть доступ. Функция os.makedirs() создает промежуточные папки в пути, если их там нет. В целом, это значит, что вы создали путь, в котором размещены папки. Лично я часто прибегал к данному решению, когда была необходимость создания журнала, с датированной структурой, например Год\Месяц\День. Давайте взглянем на пример:
Что произошло? Этот код просто создал кучу папок! Если в вашей системе все еще есть папка pytest, то в ней появится папка 2014, в которой также есть папка, в которой, удивительно, находится еще одна. Попробуйте сами, воспользовавшись рабочим путем в вашей системе.
What is the os.getcwd() method in Python?
Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.
Introduction
Getting the directory on which work is currently being done in a Python program is very essential. This can easily be achieved using the os.getcwd() .
The Python scripting language comes with a lot of built in modules which make writing python much easier and fun nonetheless. One of such inbuilt modules is the OS module.
The OS module makes available different functions that are used to communicate with the operating system. This module is part of Python’s standard utility modules.
The os.getcwd() method is one of the functions which the OS module provides.
What is the os.getcwd() method?
The os.getcwd() method is used to get the current working directory of a process.
Somewhere in your script, you can add this function anytime you wish to know or get the directory of an operation currently being carried out.
Syntax
Parameters
This function takes no parameters.
Return value
Returns a string which stands for the current working directory. This can be saved in a variable and accessed when needed.