30 Useful Methods from python OS Module - Analytics Vidhya
文章推薦指數: 80 %
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 ×
延伸文章資訊
- 1OS Module - Python - TutorialsTeacher
It is possible to automatically perform many operating system tasks. The OS module in Python prov...
- 2【python基礎】os模組的使用 - IT人
os簡介os 模組是關於作業系統操作呼叫的相關模組,對檔案進行重新命名、刪除等一系列操作,在python中可以用os模組os模組提供了一些系統級別的操作 ...
- 3Python中import os是什么意思? - 知乎
首先合法的package必须含有一个__init__.py文件,package可以包含0个或多个module(py文件)。假设aa文件夹中有test.py文件和bb文件夹,bb文件夹里面有c.p...
- 430 Useful Methods from python OS Module - Analytics Vidhya
The python os module makes this possible, it provides a means for us to interact with the underly...
- 510. Python 標準函式庫概覽— Python 3.10.4 說明文件
import os >>> dir(os) <returns a list of all module functions> >>> help(os) <returns an extensive...