Working directory python windows

Как получить и изменить текущий рабочий каталог в Python

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

Когда вы запускаете сценарий Python, в качестве текущего рабочего каталога устанавливается каталог, из которого выполняется сценарий.

Модуль os python обеспечивает переносимый способ взаимодействия с операционной системой. Модуль является частью стандартной библиотеки Python и включает методы поиска и изменения текущего рабочего каталога.

Получение текущего рабочего каталога в Python

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

Чтобы использовать методы модуля os, вы должны импортировать модуль в верхней части файла.

Ниже приведен пример, показывающий, как распечатать текущий рабочий каталог:

Результат будет выглядеть примерно так:

Изменение текущего рабочего каталога в Python

Чтобы изменить текущий рабочий каталог в Python, используйте метод chdir() .

Метод принимает один аргумент — путь к каталогу, в который вы хотите перейти. Аргумент path может быть абсолютным или относительным.

Результат будет выглядеть примерно так:

Аргумент, передаваемый методу chdir() должен быть каталогом, в противном случае NotADirectoryError исключение NotADirectoryError . Если указанный каталог не существует, возникает исключение FileNotFoundError . Если у пользователя, от имени которого выполняется сценарий, нет необходимых разрешений, возникает исключение PermissionError .

Выводы

Чтобы найти текущий рабочий каталог в Python, используйте os.getcwd() , а для изменения текущего рабочего каталога используйте os.chdir(path) .

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Работа с файлами в Python с помощью модуля OS

Обработка файлов в Python с помощью модуля os включает создание, переименование, перемещение, удаление файлов и папок, а также получение списка всех файлов и каталогов и многое другое.

В индустрии программного обеспечения большинство программ тем или иным образом обрабатывают файлы: создают их, переименовывают, перемещают и так далее. Любой программист должен обладать таким навыком. С этим руководством вы научитесь использовать модуль os в Python для проведения операций над файлами и каталогами вне зависимости от используемой операционной системы.

Важно знать, что модуль os используется не только для работы с файлами. Он включает массу методов и инструментов для других операций: обработки переменных среды, управления системными процессами, а также аргументы командной строки и даже расширенные атрибуты файлов, которые есть только в Linux.

Читайте также:  Администратор линукс вакансии без опыта

Модуль встроенный, поэтому для работы с ним не нужно ничего устанавливать.

Вывод текущей директории

Для получения текущего рабочего каталога используется os.getcwd() :

os.getcwd() возвращает строку в Юникоде, представляющую текущий рабочий каталог. Вот пример вывода:

Создание папки

Для создания папки/каталога в любой операционной системе нужна следующая команда:

После ее выполнения в текущем рабочем каталоге тут же появится новая папка с названием «folder».

Если запустить ее еще раз, будет вызвана ошибка FileExistsError , потому что такая папка уже есть. Для решения проблемы нужно запускать команду только в том случае, если каталога с таким же именем нет. Этого можно добиться следующим образом:

Функция os.path.isdir() вернет True , если переданное имя ссылается на существующий каталог.

Изменение директории

Менять директории довольно просто. Проделаем это с только что созданным:

Еще раз выведем рабочий каталог:

Создание вложенных папок

Предположим, вы хотите создать не только одну папку, но и несколько вложенных:

Это создаст три папки рекурсивно, как показано на следующем изображении:

Создание файлов

Для создания файлов в Python модули не нужны. Можно использовать встроенную функцию open() . Она принимает название файла, который необходимо создать в качестве первого параметра и желаемый режим открытия — как второй:

w значит write (запись), a — это appending (добавление данных к уже существующему файлу), а r — reading (чтение). Больше о режимах открытия можно почитать здесь.

Переименование файлов

С помощью модуля os достаточно просто переименовать файл. Поменяем название созданного в прошлом шаге.

Функция os.rename() принимает 2 аргумента: имя файла или папки, которые нужно переименовать и новое имя.

Перемещение файлов

Функцию os.replace() можно использовать для перемещения файлов или каталогов:

Стоит обратить внимание, что это перезапишет путь, поэтому если в папке folder уже есть файл с таким же именем ( renamed-text.txt ), он будет перезаписан.

Список файлов и директорий

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

А что если нужно узнать состав и этих папок тоже? Для этого нужно использовать функцию os.walk() :

os.walk() — это генератор дерева каталогов. Он будет перебирать все переданные составляющие. Здесь в качестве аргумента передано значение «.», которое обозначает верхушку дерева:

Метод os.path.join() был использован для объединения текущего пути с именем файла/папки.

Удаление файлов

Удалим созданный файл:

os.remove() удалит файл с указанным именем (не каталог).

Удаление директорий

С помощью функции os.rmdir() можно удалить указанную папку:

Для удаления каталогов рекурсивно необходимо использовать os.removedirs() :

Это удалит только пустые каталоги.

Получение информации о файлах

Для получения информации о файле в ОС используется функция os.stat() , которая выполняет системный вызов stat() по выбранному пути:

Это вернет кортеж с отдельными метриками. В их числе есть следующие:

    • st_size — размер файла в байтах
    • st_atime — время последнего доступа в секундах (временная метка)
    • st_mtime — время последнего изменения
    • st_ctime — в Windows это время создания файла, а в Linux — последнего изменения метаданных

Для получения конкретного атрибута нужно писать следующим образом:

На этой странице больше об атрибутах.

Выводы

Работать с файлами и каталогами в Python очень просто. Не имеет значения даже используемая операционная система, хотя отдельные уникальные для системы функции можно использовать: например, os.chown() или os.chmod() в Linux. Более подробно эта тема освещена в официальной документации Python.

Читайте также:  What is the copy command in linux

Подписывайтесь на канал в Дзене

Полезный контент для начинающих и опытных программистов в канале Лента Python разработчика — Как успевать больше, делать лучше и не потерять мотивацию.

Find current directory and file’s directory [duplicate]

In Python, what commands can I use to find:

  1. the current directory (where I was in the terminal when I ran the Python script), and
  2. where the file I am executing is?

13 Answers 13

To get the full path to the directory a Python file is contained in, write this in that file:

(Note that the incantation above won’t work if you’ve already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)

To get the current working directory use

Documentation references for the modules, constants and functions used above:

  • The os and os.path modules.
  • The __file__ constant
  • os.path.realpath(path) (returns «the canonical path of the specified filename, eliminating any symbolic links encountered in the path»)
  • os.path.dirname(path) (returns «the directory name of pathname path «)
  • os.getcwd() (returns «a string representing the current working directory»)
  • os.chdir(path) («change the current working directory to path «)

Current Working Directory: os.getcwd()

And the __file__ attribute can help you find out where the file you are executing is located. This SO post explains everything: How do I get the path of the current executed file in Python?

You may find this useful as a reference:

In order to get current working directory use Path.cwd() :

To get an absolute path to your script file, use Path.resolve() method:

And to get path of a directory where your script is located, access .parent (it is recommended to call .resolve() before .parent ):

Remember that __file__ is not reliable in some situations: How do I get the path of the current executed file in Python?.

Please note, that Path.cwd() , Path.resolve() and other Path methods return path objects ( PosixPath in my case), not strings. In Python 3.4 and 3.5 that caused some pain, because open built-in function could only work with string or bytes objects, and did not support Path objects, so you had to convert Path objects to strings or use Path.open() method, but the latter option required you to change old code:

As you can see open(p) does not work with Python 3.5.

PEP 519 — Adding a file system path protocol, implemented in Python 3.6, adds support of PathLike objects to open function, so now you can pass Path objects to open function directly:

Python directory

last modified September 14, 2020

Python directory tutorial shows how to work with directories in Python. We show how to create, rename, move, or list a directory in Python.

Directory definition

Directory is an organizing unit in a computer’s file system for storing and locating files. Directories are hierarchically organized into a tree of directories. Directories have parent-child relationships. A directory is sometimes also called a folder.

There are multiple functions for manipulating directories in Python. They are located in the os and pathlib modules. In the tutorial, we work with the pathlib module, which has the more modern API.

Читайте также:  Windows 10 64 bit update tool

Python create directory

The Path.mkdir creates a single directory or multiple directories, including intermediate directories.

If a directory exists, a FileExistsError is raised.

The example creates a directory with Path’s mkdir function.

When we run the program twice, an exception is thrown. To get around this issue, we can check if a directory already exists.

Before we create the directory, we check if it already exists with the Path.exists function. We also catch a possible exception.

Another solution is to use the exist_ok flag. If this flag is set to True , the FileExistsError is ignored.

In this example, we ignore the FileExistsError exceptions.

Python create temporary directory

The tempfile.TemporaryDirectory function securely creates a temporary directory. On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.

The example creates a temporary directory. When the program finishes, the directory is destroyed.

The program created a temporary directory in the special /tmp directory, which is used for such purposes on Linux.

Python rename directory

The Path.rename function renames a directory.

In the example, we rename the test directory to test2 .

Python remove directory

A directory is removed with the Path.rmdir function. The directory must be empty.

The example deletes the test2 directory.

Python move directory

The shutil.move function moves a directory.

The shutil.move recursively moves a file or directory (src) to another location (dst) and returns the destination.

There are two copy functions: copy and copy2 ; the default is copy2 . They differ how they handle file metadata. The copy2 tries to preserve all the file metadata, while the copy does not.

The example moves the contents of the doc directory to docs2 .

We create the docs directory and some files.

We run the program and show the contents of the new directory.

Python current working directory

The Path.cwd function returns a new path object representing the current directory.

The example changes directories and prints the current directory.

Python home directory

The Path.home function returns a new path object representing the user’s home directory.

The program prints the home directory of the user that launched it.

Python directory parents

The Path.parent retunrs the parent of the path and the Path.parents a sequence of ancestors of the path.

The example prints the various parents of the current working directory.

Python list directory contents

The Path.iterdir yields path objects of the directory contents. The children are yielded in arbitrary order, and the special entries ‘.’ and ‘..’ are not included.

The example lists the files and directories of the current working directory. The list is non-recursive.

Python check if path is directory

The Path.is_dir returns True if the path points to a directory.

In the example, we list all immediate subdirectories of the current working directory.

In our case, we have three subdirectories.

Python list directory recursively

The path.rglob yields all the files that match the given simple pattern recursively.

In the example, we recursively walk the contents of the parent directory and print all Python files.

In this tutorial, we have worked with directories in Python.

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