How to get current directory in Python? - ItsMyCode

文章推薦指數: 80 %
投票人數:10人

To get current directory in Python, use the os module function os.getcwd(), and if you want to change the current directory, use the os.chrdir() method. Home»Python»HowtogetcurrentdirectoryinPython?Total0Shares000000000TableofContents HideGettingtheCurrentWorkingDirectoryinPythonGetthepathofthescriptfileinPythonChangingtheCurrentWorkingDirectoryinPython ConclusionInthisarticle,wewilltakealookathowtogetcurrentdirectoryinPython.Thecurrentdirectoryisnothingbutyourworkingdirectoryfromwhichyourscriptisgettingexecuted.GettingtheCurrentWorkingDirectoryinPythonTheosmodulehasagetcwd()functionusingwhichwecanfindouttheabsolutepathoftheworkingdirectory. Syntax: os.getcwd()Parameter: NoneReturnValue: Returnsthestringwhichcontainstheabsolutepathofthecurrentworkingdirectory. BelowisanexampletoprintthecurrentworkingdirectoryinPython#Pythonprogramgetcurrentworkingdirectoryusingos.getcwd() #importingosmodule importos #Getthecurrentdirectorypath current_directory=os.getcwd() #Printthecurrentworkingdirectory print("Currentworkingdirectory:",current_directory) OutputCurrentworkingdirectory:C:\Projects\TryoutsGetthepathofthescriptfileinPythonIfyouwanttogetthepathofthecurrentscriptfile,youcoulduseavariable __file__ andpassitto the realpath methodoftheos.pathmodule. Exampletogetthepathofthecurrentscriptfile#Pythonprogramgetcurrentworkingdirectoryusingos.getcwd() #importingosmodule importos #Getthecurrentdirectorypath current_directory=os.getcwd() #Printthecurrentworkingdirectory print("Currentworkingdirectory:",current_directory) #Getthescriptpathandthefilename foldername=os.path.basename(current_directory) scriptpath=os.path.realpath(__file__) #Printthescriptfileabsolutepath print("Scriptfilepathis:"+scriptpath)OutputCurrentworkingdirectory:C:\Projects\Tryouts Scriptpathis:C:\Projects\Tryouts\main.pyChangingtheCurrentWorkingDirectoryinPython IfyouwanttochangethecurrentworkingdirectoryinPython,usethechrdir()method.Syntax: os.chdir(path)Parameters: path: Thepathofthenewdirectoryinthestringformat.  Returns: Doesn’treturnanyvalueExampletochangethecurrentworkingdirectoryinPython#Importtheosmodule importos #Printthecurrentworkingdirectory print("Currentworkingdirectory:{0}".format(os.getcwd())) #Changethecurrentworkingdirectory os.chdir('/Projects') #Printthecurrentworkingdirectory print("NewCurrentworkingdirectory:{0}".format(os.getcwd())) OutputCurrentworkingdirectory:C:\Projects\Tryouts NewCurrentworkingdirectory:C:\ProjectsConclusionTogetthecurrentworkingdirectoryinPython,usetheosmodulefunctionos.getcwd(),andifyouwanttochangethecurrentdirectory,usetheos.chrdir()method.reportthisadTotal0SharesShare 0Tweet 0Share 0Share 0Share 0SrinivasBlogger,Traveller,InvestorandTechnologist.RelatedTagschdir(),currentworkingdirectory,directory,getcwd(),os,scriptpathLeaveaReplyCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*Comment*Name*Email*WebsiteSavemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. ΔViewComments(0)SignUpforOurNewslettersGetnotifiedofthebestdealsonourWordPressthemes. SubscribeBycheckingthisbox,youconfirmthatyouhavereadandareagreeingtoourtermsofuseregardingthestorageofthedatasubmittedthroughthisform.YouMayAlsoLikePython3minutereadTableofContentsHideWhatisAttributeError:‘numpy.ndarray’objecthasnoattribute‘append’?Howtofix AttributeError:‘numpy.ndarray’objecthasnoattribute‘append’?Syntaxofnumpy.append()Parametersofnumpy.append()ReturnValueofnumpy.append()Example–Append…ViewPostPython3minutereadTableofContentsHidePythonprogramtocheckifstringisemptyornotUsinglen()funtionUsingnotoperatorUsingnot+str.strip()method Usingnot+str.isspacemethodInthisarticle,youwilllearn…ViewPostPython2minutereadTableofContentsHideendswith()Syntaxendswith()Parameterendswith()ReturnValueExample1:endswith()WithoutstartandendParametersExample2:endswith()WithstartandendParametersPassingTupletoendswith()PythonStringendswith()method…ViewPostPythonHowTo2minutereadTableofContentsHideWhatisaSquareroot?HowtocalculatetheSquarerootinPython?Usingsqrt()functionUsingpow()functionInthisarticle,youwillbelearninghowtofind…ViewPostHowToCSS2minutereadBootstrapwillprovidethedefaultGutterwidthas30pxallthetimeandthegridconsistsof12columns.Butinmostofthecasethedefaultgutterwidthof…ViewPostPython4minutereadTableofContentsHideWhatisUnpackinginPython?UnpackingusingListinPythonUnpackinglistusingunderscoreUnpackinglistusinganasteriskWhatisValueError:toomanyvaluestounpack(expected2)?Scenario1:…ViewPostTrendingTopics 1[Solved]DeprecationWarning:executable_pathhasbeendeprecated,pleasepassinaServiceobjectApril4,2022 2[Solved]Deprecationwarning:find_element_by_*commandsaredeprecated.pleaseusefind_element()insteadApril4,2022 3Solvingenvironment:failedwithinitialfrozensolve.retryingwithflexiblesolveApril3,2022reportthisadFeaturedCategoriesHowToViewPostsJavascriptViewPostsPythonreportthisad ViewPostsxx



請為這篇文章評分?