Os chdir in python

Os chdir in python

  • Python | os.ctermid() method
  • Python | os.environ object
  • Python os.chdir() method
  • Python | os.fchdir() method
  • Python | os.getcwd() method
  • Python | os.getenv() method
  • Python | os.get_exec_path() method
  • Python | os.geteuid() and seteuid() method
  • Python | os.getgrouplist() method
  • Python | os.getgroups() method
  • Python | os.getlogin() method
  • Python | os.getpgid() method
  • Python | os.getpgrp() method
  • Python | os.getpid() method
  • Python | os.getppid() method
  • Python | os.getresuid() and os.setresuid() method
  • Python | os.getuid() and os.setuid() method
  • Python | os.setregid() method
  • Python | os.setreuid() method
  • Python | os.setgroups() method
  • Python | os.getsid() method
  • Python | os.strerror() method
  • Python | os.supports_bytes_environ object
  • Python | os.umask() method
  • Python | os.link() method
  • Python | os.listdir() method
  • Python | os.mkdir() method
  • Python | os.makedirs() method
  • Python | os.mkfifo() method
  • Python | os.major() method
  • Python | os.minor() method
  • Python | os.makedev() method
  • Python | os.readlink() method
  • Python | os.remove() method
  • Python | os.removedirs() method
  • Python | os.rename() method
  • Python | os.renames() method
  • Python – os.replace() method
  • Python | os.rmdir() method
  • Python | os.scandir() method
  • Python | os.stat() method
  • Python | os.statvfs() method
  • Python | os.sync() method
  • Python | os.truncate() method
  • Python | os.unlink() method
  • os.walk() in Python
  • Python os.chdir() method
  • Python | os.abort() method
  • Python | os._exit() method
  • Python | os.fork() method
  • Python | os.kill() method
  • Python | os.nice() method
  • Python | os.system() method
  • Python | os.times() method
  • Python | os.wait() method
  • Python os.chdir() method
  • Python | os.open() method
  • Python | os.get_blocking() method
  • Python | os.isatty() method
  • Python | os.openpty() method
  • Python | os.pipe() method
  • Python | os.pipe2() method
  • Python | os.pread() method
  • Python | os.write() method
  • Python | os.pwrite() method
  • Python | os.read() method
  • Python | os.sendfile() method
  • Python | os.set_blocking() method
  • Python | os.ctermid() method
  • Python | os.environ object
  • Python os.chdir() method
  • Python | os.fchdir() method
  • Python | os.getcwd() method
  • Python | os.getenv() method
  • Python | os.get_exec_path() method
  • Python | os.geteuid() and seteuid() method
  • Python | os.getgrouplist() method
  • Python | os.getgroups() method
  • Python | os.getlogin() method
  • Python | os.getpgid() method
  • Python | os.getpgrp() method
  • Python | os.getpid() method
  • Python | os.getppid() method
  • Python | os.getresuid() and os.setresuid() method
  • Python | os.getuid() and os.setuid() method
  • Python | os.setregid() method
  • Python | os.setreuid() method
  • Python | os.setgroups() method
  • Python | os.getsid() method
  • Python | os.strerror() method
  • Python | os.supports_bytes_environ object
  • Python | os.umask() method
  • Python | os.link() method
  • Python | os.listdir() method
  • Python | os.mkdir() method
  • Python | os.makedirs() method
  • Python | os.mkfifo() method
  • Python | os.major() method
  • Python | os.minor() method
  • Python | os.makedev() method
  • Python | os.readlink() method
  • Python | os.remove() method
  • Python | os.removedirs() method
  • Python | os.rename() method
  • Python | os.renames() method
  • Python – os.replace() method
  • Python | os.rmdir() method
  • Python | os.scandir() method
  • Python | os.stat() method
  • Python | os.statvfs() method
  • Python | os.sync() method
  • Python | os.truncate() method
  • Python | os.unlink() method
  • os.walk() in Python
  • Python os.chdir() method
  • Python | os.abort() method
  • Python | os._exit() method
  • Python | os.fork() method
  • Python | os.kill() method
  • Python | os.nice() method
  • Python | os.system() method
  • Python | os.times() method
  • Python | os.wait() method
  • Python os.chdir() method
  • Python | os.open() method
  • Python | os.get_blocking() method
  • Python | os.isatty() method
  • Python | os.openpty() method
  • Python | os.pipe() method
  • Python | os.pipe2() method
  • Python | os.pread() method
  • Python | os.write() method
  • Python | os.pwrite() method
  • Python | os.read() method
  • Python | os.sendfile() method
  • Python | os.set_blocking() method
Читайте также:  Formatted output in cpp

Источник

OS Python

Основы

Введение в тему

Модуль os Python предоставляет возможность взаимодействовать с операционной системой, независимо от того, какая из них установлена на устройстве, что делает программы универсальными.

Этот модуль является частью стандартной библиотеки и не требует установки.

Модуль os предоставляет множество функций, которые можно применять при работе с операционной системой. В этом уроке Вы изучите основные возможности данной библиотеки.

os chdir и os getcwd

Функция os.chdir даёт возможность сменить директорию. При запуске скрипта базовой папкой является та, в которой этот скрипт был запущен.

Узнать полный текущий путь к рабочей папке позволяет функция os.getcwd().

Приведём пример использования обеих функций:

 
import os print("Текущая директория:", os.getcwd()) os.chdir(r"C:\Users\Dushenko\Desktop") print("Новая директория:", os.getcwd()) # Вывод: Текущая директория: C:\Users\Dushenko\AppData\Roaming\JetBrains\PyCharm2021.1\scratches Новая директория: C:\Users\Dushenko\Desktop

Листинг этой программы демонстрирует нам, что была открыта папка по умолчанию в Питоне. После этого директория была изменена при помощи os.chdir(). Затем была вызвана os.getcwd() еще раз, что продемонстрировало изменение директории.

os mkdir и os makedirs

Этот метод предназначен для создания новой папки в текущей. Выкидывает исключение OSError, если папка уже существует.

 
import os print("Содержимое текущей директории:", os.listdir()) os.mkdir('new_scratches') print("Содержимое текущей директории:", os.listdir()) # Вывод: Содержимое текущей директории: ['scratch.py'] Содержимое текущей директории: ['new_scratches', 'scratch.py']

os.makedirs — создаёт директорию, создавая при этом промежуточные директории.

 
import os print("Содержимое текущей директории:", os.listdir()) os.makedirs('new_scratches/example') print("Содержимое текущей директории:", os.listdir()) os.chdir(os.getcwd() + r'\\new_scratches') print("Содержимое директории new_scratches:", os.listdir()) # Вывод: Содержимое текущей директории: ['scratch.py'] Содержимое текущей директории: ['new_scratches', 'scratch.py'] Содержимое директории new_scratches: ['example']

os remove и os rmdir

Эта функция предназначена для удаления файлов.

 
import os print("Содержимое текущей директории:", os.listdir()) os.remove('example.txt') print("Содержимое текущей директории:", os.listdir()) # Вывод: Содержимое текущей директории: ['example.txt', 'scratch.py'] Содержимое текущей директории: ['scratch.py'] 
import os os.mkdir('example') print("Содержимое текущей директории:", os.listdir()) os.rmdir('example') print("Содержимое текущей директории:", os.listdir()) # Вывод: Содержимое текущей директории: ['example', 'scratch.py'] Содержимое текущей директории: ['scratch.py']

os rename src dst

Функция os.rename() применяется для изменения имени файлов или папок.

 
import os os.mkdir('example') print("Содержимое текущей директории:", os.listdir()) os.rename('example', 'пример') print("Содержимое текущей директории:", os.listdir()) # Вывод: Содержимое текущей директории: ['example', 'scratch.py'] Содержимое текущей директории: ['scratch.py', 'пример']

os startfile

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

 
import os print("Содержимое текущей директории:", os.listdir()) os.startfile('example.py') # Вывод: Содержимое текущей директории: ['example.py', 'scratch.py']

В результате выполнения этого кода файл ‘example.py’ откроется в программе по умолчанию. Если Питоновские файлы у Вас ассоциированы со средой обработки, то откроется в ней, иначе этот скрипт исполнится.

os walk

Функция os.walk() возвращает объект-генератор, из которого получают кортежи для каждого каталога переданной файловой иерархии.

Каждый кортеж состоит из трех элементов:

Адрес очередного каталога в виде строки.

В форме списка имена подкаталогов первого уровня вложенности для данного каталога.

В виде списка имена файлов данного каталога.

 
import os print("Содержимое текущей директории:", os.listdir()) walk = os.walk('..') for item in walk: print(item) # Вывод: … ('..\\scratches', [], ['example.py', 'scratch.py']) ('..\\ssl', [], []) …

os path

Модуль os.path включает в себя несколько функции для работы с путями файловой системы. Параметры пути должны быть переданы в формате строк или байтов. Вместо этого модуля рекомендуется использовать модуль pathlib, доступный в стандартной библиотеке Питона начиная с версии 3.4.

os path basename

Функция basename() модуля os.path возвращает базовое имя пути.

 
import os path = os.getcwd() print("Текущая директория:", path) print('Базовое имя пути:', os.path.basename(path)) # Вывод: Текущая директория: C:\Users\Dushenko\AppData\Roaming\JetBrains\PyCharm2021.1\scratches Базовое имя пути: scratches

os path dirname

Функция dirname возвращает ту часть пути, которую составляет каталог пути.

 
import os path = os.getcwd() print("Текущая директория:", path) print('Базовое имя пути:', os.path.dirname(path)) # Вывод: Текущая директория: C:\Users\Dushenko\AppData\Roaming\JetBrains\PyCharm2021.1\scratches Базовое имя пути: C:\Users\Dushenko\AppData\Roaming\JetBrains\PyCharm2021.1

os path exists

Функция exists модуля os.path проверяет, существует ли указанный файл.

 
import os print(r'Существует ли путь C:\Users:', os.path.exists(r'C:\Users')) print(r'Существует ли путь C:\Example:', os.path.exists(r'C:\Example')) # Вывод: Существует ли путь C:\Users: True Существует ли путь C:\Example: False

os path isdir os path isfile

Функции isdir и isfile проверяют присутствие или отсутствие файлов или директорий в указанном пути. isdir проверяет наличие директории, а isfile — файла.

 
import os print(r'C:\Users - это файл?', os.path.isfile(r'C:\Users'), sep='\n') print(r'C:\Users - это папка?', os.path.isdir(r'C:\Users'), sep='\n') # Вывод: C:\Users — это файл? False C:\Users — это папка? True

os path join

В разных операционных системах используется разный разделитель пути. В Виндовс это бекслеш, а в Линукс – слеш. Как же сделать объединение путей в Вашей программе универсальным?

Функция join предназначена для объединения нескольких путей в любой OS.

 
import os path = os.getcwd() print("Текущая директория:", path) print("Добавим 'example':", new_path := os.path.join(path, r"example")) print("Но существует ли этот путь?", os.path.exists(new_path)) # Вывод: Текущая директория: C:\Users\Dushenko\AppData\Roaming\JetBrains\PyCharm2021.1\scratches Добавим 'example': C:\Users\Dushenko\AppData\Roaming\JetBrains\PyCharm2021.1\scratches\example Но существует ли этот путь? False

os path split

Метод split принимает путь и возвращает кортеж, состоящий из базового имени пути и каталога пути.

 
import os path = os.getcwd() print("Текущая директория:", path) print("Базовое имя пути:", os.path.split(path)[1], sep='\n') print("Каталог пути:", os.path.split(path)[0], sep='\n') # Вывод: Текущая директория: C:\Users\Dushenko\AppData\Roaming\JetBrains\PyCharm2021.1\scratches Базовое имя пути: scratches Каталог пути: C:\Users\Dushenko\AppData\Roaming\JetBrains\PyCharm2021.1

Подведем итоги

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

Будьте внимательны: некоторые функции из этого модуля поддерживаются не всеми ОС.

Источник

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