logo

Mètode Python os.chdir().

Mòdul SO a Python proporciona funcions per interactuar amb el sistema operatiu. SO, inclou els mòduls d'utilitat estàndard de Python. Aquest mòdul proporciona una manera portàtil d'utilitzar la funcionalitat dependent del sistema operatiu.
os.chdir() mètode a Python utilitzat per canviar el directori de treball actual al camí especificat. Només necessita un sol argument com a camí de directori nou.

Sintaxi: os.chdir(camí)
Paràmetres:
Camí: Una ruta completa del directori que s'ha de canviar a una ruta de directori nova.
Devolucions: No retorna cap valor

Codi #1: Utilitzeu chdir() per canviar el directori



Python 3




Negació de les matemàtiques discretes
# 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'>)>

>

>

Sortida:

Directory changed>

Codi #2: Ús d'os.getcwd()
Per conèixer el directori de treball actual del fitxer, es pot utilitzar el mètode getcwd(). Després de canviar el camí, es pot verificar el camí del directori de treball actual mitjançant aquest mètode.

Python 3




# 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)>

>

>

Sortida:

Current working directory is: c:gfg_dir>


Codi #3: Gestionar els errors en canviar el directori

Python 3




# 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())>

>

>

genera un nombre aleatori en java

Sortida:

Inserting inside- c:gfg_dirgfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c:gfg_dirgfg>