How to change current working directory in python - thisPointer
文章推薦指數: 80 %
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
延伸文章資訊
- 1How to change current working directory in python - thisPointer
First of all we need to import python's os module i.e. ... Python's os module provides a function...
- 2How to get current directory in Python? - ItsMyCode
To get current directory in Python, use the os module function os.getcwd(), and if you want to ch...
- 3Python : How to Get the current working directory - thisPointer
It returns a string containing the current working directory. For calling this function we need t...
- 4os.path — Common pathname manipulations — Python 3.10 ...
The os.path module is always the path module suitable for the operating system Python is running ...
- 5Get and change the current working directory in Python
os.getcwd() returns the absolute path of the working directory where Python is currently running ...