30 Useful Methods from python OS Module - Analytics Vidhya

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

The python os module makes this possible, it provides a means for us to interact with the underlying operating system in many different ways ... D H M S × Home 30UsefulMethodsfrompythonOSModule Facebook Twitter Linkedin Youtube SaagaraM.B.—May17,2021 Beginner Listicle Programming Python Thisarticlewaspublishedasapartofthe DataScienceBlogathon. Introduction Manytimeswhenweworkinpythonthereareinstanceswherewewouldliketoutilisethefunctionalitiesoftheunderlyingoperatingsystem.Thepythonosmodulemakesthispossible,itprovidesameansforustointeractwiththeunderlyingoperatingsysteminmanydifferentwaysandprovidesuswithaportablewaytousetheoperatingsystemdependentfunctionalities. Forexample,itmakesitpossibleforustogetthepathofthedirectoryweareworkingwith,getthenamesofallthefilesandfolderswithinadirectory,makeanewdirectoryorremoveanexistingoneandsoon. Inthisblogletusexploresomeusefulmethodsintheosmodulethatcancomeinhandywhenyouworkonyournextproject. Beforegettingstartedletuslookatsomeofthethingsweneedtotakenoteofabouttheosmodule  Thedesignofallbuilt-inoperatingsystemdependentmodulesofPythonissuchthataslongasthesamefunctionalityisavailable,itusesthesameinterface. Extensionspeculiartoaparticularoperating systemarealsoavailablethroughtheosmodulebutusingthemisinevitablyathreat toportability. Allfunctionsacceptingpathorfilenamesacceptbothbytesandstringobjectsasinput,and ifapathorfilenameisreturnedthentheresultisalsoanobjectofthesametype. AllfunctionsinthepythonosmoduleraisetheOSError (orsubclassesthereof)wheninvalidorinaccessiblefilenamesandpaths,orotherargumentsthathavethecorrecttype,butarenotacceptedbytheoperatingsystemareencountered. Letusstartbyimportingthemodule Nowlet’sgothroughthemethodsonebyone  1.  os.name: Givesthenameoftheimportedoperatingsystemdependentmodule 2.  os.error: ItistheenvironmenterrorclassforI/OandOSError.Itisraisedwhenanyfunction      returnsanysystemrelatederror 3.  os.uname(): Givesthesystemdependentversioninformation 4. os.ctermid(): Thismethodreturnsthefilenamecorrespondingtothecontrollingterminaloftheprocess 5.os.environ: Itisamappingobjectthatrepresentsthestringenvironment.Thismappingiscapturedwhentheosmoduleisinitiallyimportedandthechangesmadethereafterintheenvironmentisnotreflectedexceptfortheonesthataremadebydirectlymodifyingos.environ. 6.os.environb: Itisamappingobjectthatrepresentstheenvironmentasbytestrings.ItisactuallytheBytesversionofos.environ.os.environandos.environbaresynchronised.Itisavailableifandonlyifsupports_bytes_environisTrue. 7. os.getenv(key,default=None): Thismethodreturnsthevalueoftheenvironmentvariablekeyifitexistsandifitdoesnotexistthenthedefaultvalueisreturned. 8.os.getcwd(): Thismethodreturnsthelocationofthecurrentworkingdirectory(CWD).TheCWDisthefolderinwhichthepythonscriptisoperating. 9.os.listdir(): Thismethodreturnsalistofallthefilesandfolderspresentinsidethespecifieddirectory.IfnodirectoryisspecifiedthenthelistoffilesandfoldersinsidetheCWDisreturned. 10.os.chdir(): ItisusedforchangingtheCWD.ItchangesCWDtothespecifiedpath. 11.os.mkdir(): Thismethodcreatesanewdirectoryaccordingtothespecifiedpath.IncasethespecifieddirectoryalreadyexistsaFileExistsErrorisraised. 12.os.makedirs(): Thismethodcreatesadirectoryrecursively.Itmeansthatwhilecreatingaleafdirectoryifanyoftheintermediateleveldirectoriesspecifiedinthepathismissingthenthemethodcreatesthemall. 13.os.remove(): Thismethoddeletesafilepath.Itcannotdeleteadirectory.IncasethespecifiedpathisthatofadirectorythentheOSErrorisraised. 14.os.rmdir(): Thismethodisusedfordeletinganemptydirectory.IfthepathdoesnotcorrespondtoanemptydirectorythenOSErrorisraised. 15.os.walk(): Thismethodgeneratesthefilenamesinadirectorytreebywalkingthetreeineitheratop-downorbottom-upmanner.os.walkreturnsageneratorthatcreatesatupleofvalues(dirpath,dirnames,filenames) 16.os.path.join(): Thismethodjoinsvariouspathcomponentswithexactlyonedirectoryseparator(“/”)followingeachnon-emptypartexceptforthelastpathcomponent.Ifthelastpathcomponentisemptythenadirectoryseparator(“/”)isputattheend.Thismethodreturnsastringwiththeconcatenatedpath. 17.os.path.basename(): Thismethodisusedtogetthebasenameinaspecifiedpath.Themethodreturnsastringvaluethatrepresentsthebasenameofthespecifiedpath. 18.os.path.split(): Thismethodsplitsthepathnameintoapairofheadandtail.Here,thetailisthelastpathnamecomponentandtheheadiseverythingthatcomesbeforeit.Themethodreturnsatupleoftheheadandtailofthespecifiedpath. 19.os.path.dirname(): Thismethodreturnsthedirectorynamefromthepathgiven.   20.os.path.commonprefix(): Thismethodreturnsthelongestpathprefixwhichisaprefixforallthepathsinthespecifiedlist. 21.os.path.getmtime(): Thismethodreturnsthetimeofthelastmodificationofthepath. 22.os.path.getatime(): Thismethodreturnsthetimeofthelastaccessofthepath. 23.os.path.getctime(): Thismethodreturnsthectimewhichisthetimeofthelastchange(Unix)ortimeofcreation(Windows)dependingonthesystem. 24.os.path.abspath(): Thismethodreturnsanormalisedabsoluteversionofthespecifiedpath. 25.os.path.normpath(): Thismethodnormalisesthespecifiedpathnamebycollapsingredundantseparatorsandup-levelreferences.   26.os.path.normcase(): Thismethodnormalisesthecaseofthespecifiedpathname. 27.os.path.isfile(): Thismethodcheckswhetherthespecifiedpathcorrespondstoanexistingfileornot.Thismethodreturnsabooleanvalue. 28.os.path.isdir(): Thismethodschecksandreportswhetherthespecifiedpathnamecorrespondstoanexistingdirectoryornot.Themethodreturnsabooleanvalue.   29.os.path.isabs(): Thismethodspecifieswhetherthegivenpathisabsoluteornot. 30.os.path.exists(): ThismethodreturnsTrueforexistingpaths.ItreturnsFalseforbrokensymboliclinks. ThemediashowninthisarticlearenotownedbyAnalyticsVidhyaandisusedattheAuthor’sdiscretion.  Related blogathonosmodulepythonPythonprogramming Tableofcontents AbouttheAuthor SaagaraM.B. OurTopAuthors viewmore Download AnalyticsVidhyaAppfortheLatestblog/Article PreviousPost BayesianApproach(GeometricBrownianMotion)inStockPriceSimulation NextPost BuildyourownNLPbasedsearchengineUsing BM25 LeaveaReplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*Cancelreply Notifymeoffollow-upcommentsbyemail.Notifymeofnewpostsbyemail.Submit Δ TopResources PythonTutorial:WorkingwithCSVfileforDataScience HarikaBonthu- Aug21,2021 JoinsinPandas:MastertheDifferentTypesofJoinsin.. AbhishekSharma- Feb27,2020 UnderstandingSupportVectorMachine(SVM)algorithmfromexamples(alongwithcode) sunil- Sep13,2017 UnderstandingRandomForest SruthiER- Jun17,2021 × WeusecookiesonAnalyticsVidhyawebsitestodeliverourservices,analyzewebtraffic,andimproveyourexperienceonthesite.ByusingAnalyticsVidhya,youagreetoourPrivacyPolicyandTermsofUse.AcceptPrivacy&CookiesPolicy Close PrivacyOverview Thiswebsiteusescookiestoimproveyourexperiencewhileyounavigatethroughthewebsite.Outofthese,thecookiesthatarecategorizedasnecessaryarestoredonyourbrowserastheyareessentialfortheworkingofbasicfunctionalitiesofthewebsite.Wealsousethird-partycookiesthathelpusanalyzeandunderstandhowyouusethiswebsite.Thesecookieswillbestoredinyourbrowseronlywithyourconsent.Youalsohavetheoptiontoopt-outofthesecookies.Butoptingoutofsomeofthesecookiesmayaffectyourbrowsingexperience. Necessary Necessary AlwaysEnabled Necessarycookiesareabsolutelyessentialforthewebsitetofunctionproperly.Thiscategoryonlyincludescookiesthatensuresbasicfunctionalitiesandsecurityfeaturesofthewebsite.Thesecookiesdonotstoreanypersonalinformation. Non-necessary Non-necessary Anycookiesthatmaynotbeparticularlynecessaryforthewebsitetofunctionandisusedspecificallytocollectuserpersonaldataviaanalytics,ads,otherembeddedcontentsaretermedasnon-necessarycookies.Itismandatorytoprocureuserconsentpriortorunningthesecookiesonyourwebsite. SAVE&ACCEPT ×



請為這篇文章評分?