Module du système d'exploitation en Python fournit des fonctions pour interagir avec le système d'exploitation. OS, fait partie des modules utilitaires standard de Python. Ce module fournit un moyen portable d'utiliser les fonctionnalités dépendantes du système d'exploitation.
os.chdir() méthode en Python utilisée pour changer le répertoire de travail actuel en chemin spécifié. Il ne prend qu'un seul argument comme nouveau chemin de répertoire.
Syntaxe: os.chdir(chemin)
Paramètres:
chemin: Un chemin complet du répertoire à remplacer par le nouveau chemin du répertoire.
Retour: Ne renvoie aucune valeur
Code n°1 : Utilisez chdir() pour changer de répertoire
Python3
comment récupérer des applications cachées
# Python3 program to change the> # directory of file using os.chdir() method> # import os library> import> os> # change the current directory> # to specified directory> os.chdir(r> 'C:UsersGfgDesktopgeeks'> )> print> (> 'Directory changed'> )> |
>
>
Sortir:
Directory changed>
Code n°2 : Utilisation de os.getcwd()
Pour connaître le répertoire de travail actuel du fichier, la méthode getcwd() peut être utilisée. Après avoir modifié le chemin, on peut vérifier le chemin du répertoire de travail actuel en utilisant cette méthode.
Python3
trier le tableau java
# import os module> import> os> # change the current working directory> # to specified path> os.chdir(> 'c:gfg_dir'> )> # verify the path using getcwd()> cwd> => os.getcwd()> # print the current directory> print> (> 'Current working directory is:'> , cwd)> |
>
>
Sortir:
Current working directory is: c:gfg_dir>
Code n°3 : Gestion des erreurs lors du changement de répertoire
Python3
# importing all necessary libraries> import> sys, os> # initial directory> cwd> => os.getcwd()> # some non existing directory> fd> => 'false_dir / temp'> # trying to insert to false directory> try> :> > os.chdir(fd)> > print> (> 'Inserting inside-'> , os.getcwd())> > # Caching the exception> except> :> > print> ('Something wrong with specified> > directory. Exception> -> ', sys.exc_info())> > # handling with finally> finally> :> > print> (> 'Restoring the path'> )> > os.chdir(cwd)> > print> (> 'Current directory is-'> , os.getcwd())> |
>
>
Sortir:
Inserting inside- c:gfg_dirgfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c:gfg_dirgfg>