Как изменить рабочую директорию python

Я пробовал так: cd C:/Users/Roma/rabota cd "C:/Users/Roma/rabota" cd ("C:/Users/Roma/rabota") Но ни один из способов не сработал в интерпретаторе: Как мне правильно сменить директорию из

Я пробовал так:

cd C:/Users/Roma/rabota
cd "C:/Users/Roma/rabota"
cd ("C:/Users/Roma/rabota")

Но ни один из способов не сработал в интерпретаторе:

введите сюда описание изображения

Как мне правильно сменить директорию из интерпретатора?

VenZell's user avatar

VenZell

19.8k5 золотых знаков43 серебряных знака61 бронзовый знак

задан 13 июл 2017 в 12:55

Yeger1993's user avatar

1

Изменить рабочую директорию можно, например, так:

import os

os.chdir(path)

Update:

В случае с Windows есть два важных нюанса:

  1. Путь необходимо обрамлять кавычками
  2. Обратные слэши в пути к целевой папке необходимо дублировать

Т.е. конкретный пример для вашего случая становится таким:

import os

os.chdir("C:\Users\Roma\rabota")

p.s. за уточнение спасибо пользователю @tanatonaut

aleks.andr's user avatar

aleks.andr

2,4892 золотых знака11 серебряных знаков22 бронзовых знака

ответ дан 13 июл 2017 в 13:01

VenZell's user avatar

VenZellVenZell

19.8k5 золотых знаков43 серебряных знака61 бронзовый знак

3

Читайте документацию:

os.chdir(path)

ответ дан 13 июл 2017 в 13:01

aleks.andr's user avatar

aleks.andraleks.andr

2,4892 золотых знака11 серебряных знаков22 бронзовых знака

Добавьте Python в системную переменную, делается это так:

ПКМ по Мой компьютер > Свойства > Дополнительные параметры системы > Переменные среды > Выбираете переменную Path > Изменить > Вставляете туда путь к Python.

Готово

Теперь откройте терминал и перейдите в нужную директорию, к примеру cd C://Users/User/Desktop и после этого напишите в терминал python. Теперь Вы в этой директории.

Вот и всё.

ответ дан 13 июл 2017 в 13:04

Pavel Durmanov's user avatar

Pavel DurmanovPavel Durmanov

5,6083 золотых знака21 серебряный знак43 бронзовых знака

1

16.10.2020
Python

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

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

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

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

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

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

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

# Import the os module
import os

# Get the current working directory
cwd = os.getcwd()

# Print the current working directory
print("Current working directory: {0}".format(cwd))

# Print the type of the returned object
print("os.getcwd() returns an object of type: {0}".format(type(cwd)))

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

Current working directory: /home/linuxize/Desktop
os.getcwd() returns an object of type: <class 'str'>

Если вы хотите найти каталог, в котором находится скрипт, используйте os.path.realpath(__file__) . Он вернет строку, содержащую абсолютный путь к запущенному скрипту.

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

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

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

Вот пример:

# Import the os module
import os

# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

# Change the current working directory
os.chdir('/tmp')

# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

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

Current working directory: /home/linuxize/Desktop
Current working directory: /tmp

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

# Import the os module
import os

path = '/var/www'

try:
    os.chdir(path)
    print("Current working directory: {0}".format(os.getcwd()))
except FileNotFoundError:
    print("Directory: {0} does not exist".format(path))
except NotADirectoryError:
    print("{0} is not a directory".format(path))
except PermissionError:
    print("You do not have permissions to change to {0}".format(path))

Выводы

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

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

  1. Создайте каталог на Python
  2. Получить текущую директорию в Python
  3. Каталоги списков на Python
  4. Изменение рабочей директории
  5. Переименование и удаление каталога

Учебное пособие по Pythonскому языку - Работа с каталогами файлов

В Python, если вы выполняете операции с каталогами, вам необходимо импортировать модуль os. Функции модуля os могут быть использованы для выполнения файловых операций и операций с каталогами.

Создайте каталог на Python

Новый каталог может быть создан с помощью метода mkdir(). Вы должны указать путь, в котором вы хотите создать каталог. Если путь не указан, то каталог будет создан в текущем каталоге.

>>> import os
>>> os.mkdir("PythonTutorials")

Новый каталог с именем PythonTutorials будет создан в текущем рабочем каталоге.

Получить текущую директорию в Python

Метод getcwd() используется для получения текущей рабочей директории,

>>> import os
>>> print(os.getcwd())
C:UsersHPAppDataLocalProgramsPythonPython36-32

Каталоги списков на Python

Для перечисления файлов и подкаталогов используется метод listdir(). Он перечисляет файлы и подкаталоги файла скрипта Python, если нет аргументов. В противном случае он перечисляет содержимое заданного пути.

>>> import os
>>> print(os.listdir())
['DLLs', 'Doc', 'get-pip.py', 'hello.py', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python36.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']
>>> print(os.listdir(r"C:Program Files"))
['7-Zip', 'Common Files', 'Microsoft Office', 'Windows Sidebar']

Изменение рабочей директории

Для изменения текущей рабочей директории используется метод chdir().

>>> import os
>>> os.chdir("C:/Users/HP/Desktop/Code")
>>> print(os.getcwd())
C:UsersHPDesktopCode

Переименование и удаление каталога

Переименовать каталог

Файл или каталог может быть переименован с помощью функции rename().

>>> import os
>>> os.rename("PythonTutorials", "Python")

Новое имя каталога теперь Python.

Удаление каталога

Каталог может быть удален с помощью метода rmdir().

>>> import os
>>> os.rmdir('Python')

Он удаляет из системы каталог Python.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    The OS module in Python is used for interacting with the operating system. This module comes under Python’s standard utility module so there is no need to install it externally. 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.
    To change the current working directory(CWD) os.chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.
    Note: The current working directory is the folder in which the Python script is operating.
     

    Syntax: os.chdir(path)
    Parameters: 
    path: A complete path of the directory to be changed to the new directory path.
    Returns: Doesn’t return any value 
     

    Example #1: We will first get the current working directory of the script and then we will change it. Below is the implementation. 
     

    Python3

    import os

    def current_path():

        print("Current working directory before")

        print(os.getcwd())

        print()

    current_path()

    os.chdir('../')

    current_path()

    Output: 
     

    Current working directory before
    C:UsersNikhil AggarwalDesktopgfg
    
    Current working directory after
    C:UsersNikhil AggarwalDesktop

    Example #2: Handling the errors while changing the directory. 
     

    Python3

    import sys, os

    cwd = os.getcwd()

    fd = 'false_dir/temp'

    try:

        print("Inserting inside-", os.getcwd())

        os.chdir(fd)

    except:

        print("Something wrong with specified directory. Exception- ")

        print(sys.exc_info())

    finally:

        print()

        print("Restoring the path")

        os.chdir(cwd)

        print("Current directory is-", os.getcwd())

    Output:
     

    Inserting inside- C:UsersNikhil AggarwalDesktopgfg
    Something wrong with specified directory. Exception- 
    (<class ‘FileNotFoundError’>, FileNotFoundError(2, ‘The system cannot find the path specified’), <traceback object at 0x00000268184630C8>)
    Restoring the path 
    Current directory is- C:UsersNikhil AggarwalDesktopgfg 
     

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    The OS module in Python is used for interacting with the operating system. This module comes under Python’s standard utility module so there is no need to install it externally. 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.
    To change the current working directory(CWD) os.chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.
    Note: The current working directory is the folder in which the Python script is operating.
     

    Syntax: os.chdir(path)
    Parameters: 
    path: A complete path of the directory to be changed to the new directory path.
    Returns: Doesn’t return any value 
     

    Example #1: We will first get the current working directory of the script and then we will change it. Below is the implementation. 
     

    Python3

    import os

    def current_path():

        print("Current working directory before")

        print(os.getcwd())

        print()

    current_path()

    os.chdir('../')

    current_path()

    Output: 
     

    Current working directory before
    C:UsersNikhil AggarwalDesktopgfg
    
    Current working directory after
    C:UsersNikhil AggarwalDesktop

    Example #2: Handling the errors while changing the directory. 
     

    Python3

    import sys, os

    cwd = os.getcwd()

    fd = 'false_dir/temp'

    try:

        print("Inserting inside-", os.getcwd())

        os.chdir(fd)

    except:

        print("Something wrong with specified directory. Exception- ")

        print(sys.exc_info())

    finally:

        print()

        print("Restoring the path")

        os.chdir(cwd)

        print("Current directory is-", os.getcwd())

    Output:
     

    Inserting inside- C:UsersNikhil AggarwalDesktopgfg
    Something wrong with specified directory. Exception- 
    (<class ‘FileNotFoundError’>, FileNotFoundError(2, ‘The system cannot find the path specified’), <traceback object at 0x00000268184630C8>)
    Restoring the path 
    Current directory is- C:UsersNikhil AggarwalDesktopgfg 
     

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

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

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

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

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

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

    import os
    
    # вывести текущую директорию
    print("Текущая деректория:", os.getcwd())
    

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

    Текущая деректория: C:python3bin
    

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

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

    # создать пустой каталог (папку)
    os.mkdir("folder")
    

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

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

    # повторный запуск mkdir с тем же именем вызывает FileExistsError, 
    # вместо этого запустите:
    if not os.path.isdir("folder"):
         os.mkdir("folder")
    

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

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

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

    # изменение текущего каталога на 'folder'
    os.chdir("folder")
    

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

    # вывод текущей папки
    print("Текущая директория изменилась на folder:", os.getcwd())
    

    Вывод:

    Текущая директория изменилась на folder: C:python3binfolder
    

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

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

    # вернуться в предыдущую директорию
    os.chdir("..")
    
    # сделать несколько вложенных папок
    os.makedirs("nested1/nested2/nested3")
    

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

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

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

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

    # создать новый текстовый файл
    text_file = open("text.txt", "w")
    # запить текста в этот файл
    text_file.write("Это текстовый файл")
    

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

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

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

    # переименовать text.txt на renamed-text.txt
    os.rename("text.txt", "renamed-text.txt")
    

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

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

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

    # заменить (переместить) этот файл в другой каталог
    os.replace("renamed-text.txt", "folder/renamed-text.txt")
    

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

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

    # распечатать все файлы и папки в текущем каталоге
    print("Все папки и файлы:", os.listdir())
    

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

    Все папки и файлы: ['folder', 'handling-files', 'nested1', 'text.txt']
    

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

    # распечатать все файлы и папки рекурсивно
    for dirpath, dirnames, filenames in os.walk("."):
        # перебрать каталоги
        for dirname in dirnames:
            print("Каталог:", os.path.join(dirpath, dirname))
        # перебрать файлы
        for filename in filenames:
            print("Файл:", os.path.join(dirpath, filename))
    

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

    Каталог: .folder
    Каталог: .handling-files
    Каталог: .nested1
    Файл: .text.txt
    Файл: .handling-fileslisting_files.py
    Файл: .handling-filesREADME.md
    Каталог: .nested1nested2
    Каталог: .nested1nested2nested3
    

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

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

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

    # удалить этот файл
    os.remove("folder/renamed-text.txt")
    

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

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

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

    # удалить папку
    os.rmdir("folder")
    

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

    # удалить вложенные папки
    os.removedirs("nested1/nested2/nested3")
    

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

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

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

    open("text.txt", "w").write("Это текстовый файл")
    
    # вывести некоторые данные о файле
    print(os.stat("text.txt"))
    

    Вывод:

    os.stat_result(st_mode=33206, st_ino=14355223812608232, st_dev=1558443184, st_nlink=1, st_uid=0, st_gid=0, st_size=19, st_atime=1575967618, st_mtime=1575967618, st_ctime=1575966941)
    

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

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

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

    # например, получить размер файла
    print("Размер файла:", os.stat("text.txt").st_size)
    

    Вывод:

    Размер файла: 19
    

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

    Выводы

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

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

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

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

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

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

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

    # Импорт модуля os
    import os
    
    # Получить текущий рабочий каталог
    cwd = os.getcwd()
    
    # Печать текущего рабочего каталога
    print("Текущий рабочий каталог: {0}".format(cwd))
    
    # Выведите тип возвращаемого объекта
    print("os.getcwd() возвращает объект типа: {0}".format(type(cwd)))
    

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

    Текущий рабочий каталог: /home/AndreyEx/Desktop
    os.getcwd() возвращает объект типа: <class 'str'>
    

    Если вы хотите найти каталог, в котором находится сценарий, используйте os.path.realpath(__file__). Он вернет строку, содержащую абсолютный путь к запущенному скрипту.

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

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

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

    Вот пример:

    # Импорт модуля os
    import os
    
    # Печать текущего рабочего каталога
    print("Текущий рабочий каталог: {0}".format(os.getcwd()))
    
    # Изменение текущего рабочего каталога
    os.chdir('/tmp')
    
    # Печать текущего рабочего каталога
    print("Текущий рабочий каталог: {0}".format(os.getcwd()))
    

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

    Текущий рабочий каталог: /home/Andreyex/Desktop
    Текущий рабочий каталог: /tmp
    

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

    # Импорт модуля os
    import os
    
    path = '/var/www'
    
    try:
        os.chdir(path)
        print("Текущий рабочий каталог: {0}".format(os.getcwd()))
    except FileNotFoundError:
        print("Каталог: {0} не существует".format(path))
    except NotADirectoryError:
        print("{0} не каталог".format(path))
    except PermissionError:
        print("У вас нет прав на изменение {0}".format(path))
    

    Вывод

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

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

    Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

    In this tutorial, you’ll learn how to use Python to get and change (set) the working directory. Being able to work with the file system is a great skill to learn for a Python developer of any skill level. Being able to get and to change the working directory while in a Python script allows you to easily work with relative paths. This allows you to easily write paths to that are relative to the working directory.

    By the end of this tutorial, you’ll have learned:

    • An overview of working with working directories using the Python os library
    • How to use the Python os library to get the working directory
    • How to change the working directory with Python
    • How to troubleshoot different error codes like NotADirectoryError or FileNotFoundError errors

    Being able to work with and move around file systems is an important skill. This is especially true in data science where you may have directories for data, models, and scripts. Being able to traverse these directories without using paths fixed to a given computer allows you to build more flexible code that can move across computers.

    The Quick Answer: Use os.getcwd() and os.chdir()

    Quick Answer - Get and Change Working Directory Python

    How to get and set a working directory in Python

    What is the Python os Library

    The Python os module a built-in library allows us to perform common operating system tasks. Because the library is built into Python, you can easily import is directly, such as shown below:

    # Importing the os Module
    import os

    The module abstracts a number of helpful operating system operations. This is particularly helpful when developing scripts that are intended to work across different operating systems. The os module has a number of helpful functions. For example, it can be used to copy files using Python or to delete files using Python.

    Python Get and Set Working Directory Snapshot

    The key functions to use to get and change your current working directory in Python

    In this section, you’ll learn how to use the os library to get the current working directory in Python. By knowing the working directory, we can files in the directory by using relative paths. This allows us to build scripts that can easily move from one system to another, as long as the relative directory is the same.

    We can use the Python os .getcwd() function to get the current working directory. getcwd stands for get current working directory.

    Let’s see what this looks like:

    # Get Current Working Directory with os.getcwd()
    import os
    cwd = os.getcwd()
    
    print('Current Working Directory is: ', cwd)
    # Returns: Current Working Directory is:  /Users/datagy

    The function doesn’t accept any arguments and returns a unicode representation of our current working directory. The format of the outputted directory will, of course, vary from operating system to operating system. In the above example, I’m running on a the script on a Mac OS computer. On a Windows computer, you may encounter a result such as C:UsersdatagyDocuments.

    If you want to find the path to the file that is currently running your code (meaning you get the path to directory as well), you can use the os library as well. Simply assign os.path.realpath(__file__) to a variable and you can access it. The __file__ variable is used to identify the current file being imported.

    Now that you know how to get the current working directory in Python, let’s see how we can use it change (or set) the working directory.

    Change the Working Directory with Python OS

    The Python os library comes with a helpful function that works similar to the getcwd() function. The chdir() function allows us to change the working directory. Unlike the getcwd() function, this function does accept a parameter and doesn’t return anything.

    We can pass in either an absolute path or a relative path. Passing in an absolute path gives us the benefit of being explicit about where we want to change our working directory to. Using a relative path affords us the ability to reuse our script across different file systems, without knowing exactly where the script is running from.

    Let’s see how the function works by using Python to change a working directory using an absolute path:

    # Change the current working directory with os.chdir()
    import os
    cwd = os.getcwd()
    print('Current Working Directory is: ', cwd)
    
    absolute_path = '/Users/datagy/Documents'
    os.chdir(absolute_path)
    
    print('New working directory is: ', os.getcwd())
    
    # Returns:
    # Current Working Directory is:  /Users/datagy
    # New working directory is:  /Users/datagy/Documents

    The example above is a bit verbose: really, you just need to call os.chdir(absolute_path). However, I wanted to illustrate how the changing of directories could work.

    Now, let’s take a look at changing working directories using relative paths in Python. To move up a folder with a relative path you can simply use ../, while moving down in the current directory involves simply adding that directory name into the script.

    Let’s take a look at an example where we move down into a directory and then use relative paths to move back up:

    # Change the current working directory with os.chdir()
    import os
    print('Current Working Directory is: ', os.getcwd())
    
    # Move down a directory to 'Documents'
    os.chdir('Documents')
    
    # Confirm the current directory
    print('Current Working Directory is: ', os.getcwd())
    
    # Use relative paths to move up a directory
    os.chdir('../')
    
    # Confirm the current directory
    print('Current Working Directory is: ', os.getcwd())
    
    # Returns:
    # Current Working Directory is:  /Users/datagy
    # Current Working Directory is:  /Users/datagy/Documents
    # Current Working Directory is:  /Users/datagy

    We can see here that we used relative paths to move down a directory and then back up. This allows us to take this code from computer to computer – as long as the directory structure exists, the program will run without fail. Check out this tutorial to learn how to check if a file or directory exists in Python.

    Handling Error Codes with Python OS

    Working with file systems is never easy. There is plenty of room for typos to be made or user error that accidentally removes a directory that your code depends on. When changing a directory, the os.chdir() function expects a directory as its input. If, for example a file is passed in, then Python will raise a NotADirectoryError.

    If you attempt to traverse the file system to a directory that doesn’t exist, then a FileNotFoundError (or an IOError) is raised. If you do not have sufficient permissions to move into a directory, Python will raise a PermissionError.

    Being aware of these errors codes and why they occur is an important process. It allows you to be more prepared in troubleshooting your programs and finding ways to solve your errors.

    Conclusion

    In this tutorial, you learned how to use Python to get a current working directory and how to use it to set a working directory. Being able to work with file systems and moving between directories allows you to built programs with growing complexity. This can be particularly important in data science when you’re working with directories that contains scripts and directories that contain data. It allows you to organize your files into logical directories that complement the set up of your program.

    To learn more about the Python os library, check out the official documentation here.

    Related Articles

    Check out the articles below to learn about similar topics:

    • Python: Copy a File (4 Different Ways)
    • Python Delete a File or Directory: A Complete Guide
    • Python: Get a File’s Extension (Windows, Mac, and Linux)

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Как изменить путь установки блюстакс
  • Как изменить рабочую директорию git
  • Как изменить путь установки visual studio 2019
  • Как изменить рабочую дату на компьютере
  • Как изменить путь установки valorant

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии