How to change current working directory in python - thisPointer

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

First of all we need to import python's os module i.e. ... Python's os module provides a function to change the current working directory i.e. ... It changes the ... Skiptocontent Inthisarticlewewilldiscusshowtochangethecurrentworkingdirectoryinpython. Currentworkingdirectoryisthedirectoryinwhichprogramisrunning. ChangeCurrentWorkingDirectoryinPython Firstofallweneedtoimportpython’sosmodulei.e. importos Python’sosmoduleprovidesafunctiontochangethecurrentworkingdirectoryi.e. os.chdir(path) Itchangesthecurrentworkingdirectorytothegivenpath. Let’sunderstandbyanexample, Advertisements Firstprintthecurrentworkingdirectoryusingos.getcwd()i.e. print("CurrentWorkingDirectory",os.getcwd()) Nowlet’schangethecurrentworkingdirectoryusingos.chdir(path)i.e. os.chdir("/home/varun/temp") Ifthegivenpathdon’texistthenos.chdir()withthrowerror:FileNotFoundError. Thereforeweshouldeithercallitusingtry/excepti.e. try: #ChangethecurrentworkingDirectory os.chdir("/home/varun/temp") print("Directorychanged") exceptOSError: print("Can'tchangetheCurrentWorkingDirectory") orcheckifthenewdirectoryexistsbeforechangingtheworkingdirectoryi.e. #CheckifNewpathexists ifos.path.exists("/home/varun/temp"): #ChangethecurrentworkingDirectory os.chdir("/home/varun/temp") else: print("Can'tchangetheCurrentWorkingDirectory") Completeexampleisasfollows, importos defmain(): print("CurrentWorkingDirectory",os.getcwd()) try: #ChangethecurrentworkingDirectory os.chdir("/home/varun/temp") print("Directorychanged") exceptOSError: print("Can'tchangetheCurrentWorkingDirectory") print("CurrentWorkingDirectory",os.getcwd()) #CheckifNewpathexists ifos.path.exists("/home/varun/temp"): #ChangethecurrentworkingDirectory os.chdir("/home/varun/temp") else: print("Can'tchangetheCurrentWorkingDirectory") print("CurrentWorkingDirectory",os.getcwd()) if__name__=='__main__': main() Output: CurrentWorkingDirectory/home/varun/Documents/blog/pythonSamples/FileSamples Directorychanged CurrentWorkingDirectory/home/varun/temp CurrentWorkingDirectory/home/varun/temp   PandasTutorials-LearnDataAnalysiswithPython   PandasTutorialPart#1-IntroductiontoDataAnalysiswithPython PandasTutorialPart#2-BasicsofPandasSeries PandasTutorialPart#3-Get&SetSeriesvalues PandasTutorialPart#4-Attributes&methodsofPandasSeries PandasTutorialPart#5-AddorRemovePandasSerieselements PandasTutorialPart#6-IntroductiontoDataFrame PandasTutorialPart#7-DataFrame.loc[]-SelectRows/ColumnsbyIndexing PandasTutorialPart#8-DataFrame.iloc[]-SelectRows/ColumnsbyLabelNames PandasTutorialPart#9-FilterDataFrameRows PandasTutorialPart#10-Add/RemoveDataFrameRows&Columns PandasTutorialPart#11-DataFrameattributes&methods PandasTutorialPart#12-HandlingMissingDataorNaNvalues PandasTutorialPart#13-IterateoverRows&ColumnsofDataFrame PandasTutorialPart#14-SortingDataFramebyRowsorColumns PandasTutorialPart#15-MergingorConcatenatingDataFrames PandasTutorialPart#16-DataFrameGroupByexplainedwithexamples   AreyoulookingtomakeacareerinDataSciencewithPython? DataScienceisthefuture,andthefutureisherenow.DataScientistsarenowthemostsought-afterprofessionalstoday.TobecomeagoodDataScientistortomakeacareerswitchinDataScienceonemustpossesstherightskillset.WehavecuratedalistofBestProfessionalCertificateinDataSciencewithPython.ThesecourseswillteachyoutheprogrammingtoolsforDataSciencelikePandas,NumPy,Matplotlib,SeabornandhowtousetheselibrariestoimplementMachinelearningmodels. CheckouttheDetailedReviewofBestProfessionalCertificateinDataSciencewithPython. Remember,DataSciencerequiresalotofpatience,persistence,andpractice.So,startlearningtoday. JoinaLinkedInCommunityofPythonDevelopers Postnavigation ←PreviousPostNextPost→ RelatedPosts 2thoughtson“Howtochangecurrentworkingdirectoryinpython?” Hi,itdidn’twork.Wouldyouhelpme? Igottheerrormessagebelow: ————————————————————————— NameErrorTraceback(mostrecentcalllast) in —->1print(“CurrentWorkingDirectory”,os.getcwd()) NameError:name‘os’isnotdefined Reply Thiserrorisbecauseyouhavenotimportedtheosmodulebeforeusingthat.Youcanimporttheosmoduleasfollows, importos Youcancopythecompleteexampleinabovecodeandtry,itwillwork. Ihavealsoupdatedtheimportosstepinarticle. Thanks Reply LeaveaCommentCancelReplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*Typehere..Name* Email* Website Δ ThissiteusesAkismettoreducespam.Learnhowyourcommentdataisprocessed. Advertisements Advertisements RecentPosts RemoverowswithNaNvaluesfromNumpyArray–Python RemoveelementsfromNumPyArraybyIndex AddavaluetoeachelementofanarrayinPython ReplaceLastCharacterofaStringinC++ ReplaceFirstCharacterinastringinC++ ReplacealloccurrencesofacharacterinStringinC++ Replaceallcharactersinstringwithasterisks–Python ReplaceLastoccurrenceofaStringinPython ReplacewordsinastringusingdictionaryinPython ReplacefirstoccurrenceofasubstringinPython PythonTutorialsLookingforSomething Searchfor: Search Wevalueyourprivacy Toprovidethebestexperiences,weusetechnologieslikecookiestostoreand/oraccessdeviceinformation.ConsentingtothesetechnologieswillallowustoprocessdatasuchasbrowsingbehaviororuniqueIDsonthissite.Notconsentingorwithdrawingconsent,mayadverselyaffectcertainfeaturesandfunctions. Functional Functional Alwaysactive Thetechnicalstorageoraccessisstrictlynecessaryforthelegitimatepurposeofenablingtheuseofaspecificserviceexplicitlyrequestedbythesubscriberoruser,orforthesolepurposeofcarryingoutthetransmissionofacommunicationoveranelectroniccommunicationsnetwork. Preferences Preferences Thetechnicalstorageoraccessisnecessaryforthelegitimatepurposeofstoringpreferencesthatarenotrequestedbythesubscriberoruser. Statistics Statistics Thetechnicalstorageoraccessthatisusedexclusivelyforstatisticalpurposes. Thetechnicalstorageoraccessthatisusedexclusivelyforanonymousstatisticalpurposes.Withoutasubpoena,voluntarycomplianceonthepartofyourInternetServiceProvider,oradditionalrecordsfromathirdparty,informationstoredorretrievedforthispurposealonecannotusuallybeusedtoidentifyyou. Marketing Marketing Thetechnicalstorageoraccessisrequiredtocreateuserprofilestosendadvertising,ortotracktheuseronawebsiteoracrossseveralwebsitesforsimilarmarketingpurposes. Manageoptions Manageservices Managevendors Readmoreaboutthesepurposes Accept Deny Viewpreferences Savepreferences Viewpreferences {title} {title} {title} Wevalueyourprivacy Toprovidethebestexperiences,weusetechnologieslikecookiestostoreand/oraccessdeviceinformation.ConsentingtothesetechnologieswillallowustoprocessdatasuchasbrowsingbehaviororuniqueIDsonthissite.Notconsentingorwithdrawingconsent,mayadverselyaffectcertainfeaturesandfunctions. Functional Functional Alwaysactive Thetechnicalstorageoraccessisstrictlynecessaryforthelegitimatepurposeofenablingtheuseofaspecificserviceexplicitlyrequestedbythesubscriberoruser,orforthesolepurposeofcarryingoutthetransmissionofacommunicationoveranelectroniccommunicationsnetwork. Preferences Preferences Thetechnicalstorageoraccessisnecessaryforthelegitimatepurposeofstoringpreferencesthatarenotrequestedbythesubscriberoruser. Statistics Statistics Thetechnicalstorageoraccessthatisusedexclusivelyforstatisticalpurposes. Thetechnicalstorageoraccessthatisusedexclusivelyforanonymousstatisticalpurposes.Withoutasubpoena,voluntarycomplianceonthepartofyourInternetServiceProvider,oradditionalrecordsfromathirdparty,informationstoredorretrievedforthispurposealonecannotusuallybeusedtoidentifyyou. Marketing Marketing Thetechnicalstorageoraccessisrequiredtocreateuserprofilestosendadvertising,ortotracktheuseronawebsiteoracrossseveralwebsitesforsimilarmarketingpurposes. Manageoptions Manageservices Managevendors Readmoreaboutthesepurposes Accept Deny Viewpreferences Savepreferences Viewpreferences {title} {title} {title} Manageconsent Manageconsent ScrolltoTop



請為這篇文章評分?