OS modul i Python giver funktioner til at interagere med operativsystemet. OS, kommer under Pythons standardværktøjsmoduler. Dette modul giver en bærbar måde at bruge operativsystemafhængig funktionalitet på.
os.chdir() metode i Python bruges til at ændre den aktuelle arbejdsmappe til specificeret sti. Det kræver kun et enkelt argument som ny mappesti.
Syntaks: os.chdir(sti)
Parametre:
sti: En komplet sti til bibliotek, der skal ændres til ny katalogsti.
Vender tilbage: Returnerer ingen værdi
Kode #1: Brug chdir() til at ændre mappen
Python3
css-justeringsbilleder
# 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'> )> |
>
>
Produktion:
Directory changed>
Kode #2: Brug af os.getcwd()
For at kende filens aktuelle arbejdsmappe kan getcwd()-metoden bruges. Efter at have ændret stien, kan man verificere stien til den aktuelle arbejdsmappe ved hjælp af denne metode.
Python3
# 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)> |
>
>
Produktion:
Current working directory is: c:gfg_dir>
Kode #3: Håndtering af fejl under ændring af mappe
Python3
hvordan man kender skærmstørrelsen
# 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())> |
>
>
Produktion:
Inserting inside- c:gfg_dirgfg Something wrong with specified directory. Exception- Restoring the path Current directory is- c:gfg_dirgfg>