Python List Files in a Directory: Step-By-Step Guide - Career ...

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

The Python os library is used to list the files in a directory. The Python os.listdir() method returns a list of every file and folder in a ... Exploreyourtrainingoptionsin10minutes GetMatched X Back BrowseBootcamps PopularBootcamps BestCodingBootcamps BestOnlineBootcamps BestWebDesignBootcamps BestDataScienceBootcamps BestTechnologySalesBootcamps BestDataAnalyticsBootcamps BestCybersecurityBootcamps BestProductManagementBotcamps BestProjectManagementBootcamps BestDigitalMarketingBootcamps BootcampsNearYou NewYork LosAngeles SanFrancisco Atlanta Chicago Seattle SanDiego Houston BrowseAllLocations ExplorebySubject Python WebDevelopment DigitalMarketing iOS Java JavaScript SQL MachineLearning SeeAllSubjects LearnforFree BrowseQuestionsFromOthers Bootcamps101 DataScience SoftwareEngineering Full-StackDevelopment JavaScript JobSearch CareerChanges ViewallCareerDiscussions BrowseTopCareers SoftwareEngineering WebDevelopment MobileAppDevelopment DataScience Cybersecurity ProductManagement DigitalMarketing UX/UIDesign ChoosingaBootcamp WhatisaCodingBootcamp? AreCodingBootcampsWorthIt? HowtoChooseaCodingBootcamp BestOnlineCodingBootcampsandCourses BestFreeBootcampsandCodingTraining CodingBootcampvs.CommunityCollege CodingBootcampvs.Self-Learning Bootcampsvs.Certifications:Compared ReadStoriesfromStudents PayingforaBootcamp HowtoPayforCodingBootcamp UltimateGuidetoCodingBootcampLoans BestCodingBootcampScholarshipsandGrants EducationStipendsforCodingBootcamps GetYourCodingBootcampSponsoredbyYourEmployer GIBillandCodingBootcamps OtherTopicsinTech TechIntevriews CareerAdvice Python HTML CSS JavaScript Git Java C++ Startmyjourney Community CareerGuides Schools&Applications PrepCourses&Scholarships Resources LiveEvents Stories About Company Jobs Values Publication Press ReskillAmerica PartnerWithUs HomePythonTutorialsPythonListFilesinaDirectory:Step-By-StepGuide Facebook Twitter LinkedIn ThePythonoslibraryisusedtolistthefilesinadirectory.ThePythonos.listdir()methodreturnsalistofeveryfileandfolderinadirectory.os.walk()functionreturnsalistofeveryfileinanentirefiletree. Often,whenyou’reworkingwithfilesinPython,you’llencountersituationswhereyouwanttolistthefilesinadirectory.Forinstance,youmaywanttofindallofthePythonfilesinafolder. ThePythonoslibraryoffersanumberofmethodsthatcanbeusedtolistfilesinadirectory.Thistutorialwilldiscusshowtouseos.listdir()togetthefilesandfoldersinadirector.We’llalsotalkaboutusingos.walk()togetthefilesandfoldersinadirectoryandinitssubdirectories. PythonosLibrary ThePythonoslibraryprovidesanumberoffunctionsthatyoucanusetoworkwithoperatingsystems.Thefunctionsincludedintheosmoduleworkonanymodernoperatingsystem,whetheritisWindows,Linux,orMac. Sinceosisanexternallibrary,weneedtoimportitintoourcodebeforewestartusingit.WecandosousingaPythonimportstatement: importos Nowthatwe’veimportedtheoslibraryintoourcode,wecanstartusingitsfunctionstolistitemsinadirectory. Pythonos.listdir() InPython,theos.listdir()methodlistsfilesandfoldersinagivendirectory.Themethoddoesnotreturnspecialentriessuchas‘.’and‘..’,whichtheoperatingsystemusestonavigatethroughdifferentdirectories. os.listdir()alsodoesnotreturnfilesandfoldersbeyondthefirstleveloffolders.Inotherwords,os.listdir()doesnotreturnanythingwithinsubfoldersdiscoveredbythemethod. 81%ofparticipantsstatedtheyfeltmoreconfidentabouttheirtechjobprospectsafterattendingabootcamp.Getmatchedtoabootcamptoday. FindYourBootcampMatch Theaveragebootcampgradspentlessthansixmonthsincareertransition,fromstartingabootcamptofindingtheirfirstjob. Startyourcareerswitchtoday »MORE: PythonSyntaxError:‘return’outsidefunctionSolutionTheos.listdir()functionacceptsoneparameter:thefilepathofthedirectorywhosefileandfoldernamesyouwanttoretrieve.  Here’sthesyntaxforthelistdirmethod: os.listdir(path) Let’swalkthroughanexampletoshowcasehowtousethismethodinaPythonprogram.  os.listdir()PythonExample SaythatwearecreatingaprogramthatanalyzesthestockmarketperformanceofNetflixoverthelastdecade.Wehaveafolder(name:/home/data_analysis/netflix)withallofourrawdata,andbeforeourprogramstartsrunning,wewanttochecktomakesurethatthefileraw_data_2019.csvexistswithinthatfolder. Inordertofunctionproperly,ourprogramneedsthatparticularfiletobestoredinthatparticularfolder. Wecouldusethefollowingcodetoretrievealistofthefilesinthe/home/data_analysis/netflixworkdirectory: importos path='/home/data_analysis/netflix' files=os.listdir(path) forfinfiles: print(f) Ourprogramretrievesalistofallfilesandfoldersinthespecifieddirectoryandreturnsthefollowing: FindYourBootcampMatch CareerKarmamatchesyouwithtoptechbootcamps Getexclusivescholarshipsandprepcourses Pleaseenteravalidphonenumber GetMatched BycontinuingyouagreetoourTermsofServiceandPrivacyPolicy,andyouconsenttoreceiveoffersandopportunitiesfromCareerKarmabytelephone,textmessage,andemail. README.md app.py raw_data_2016.csv raw_data_2017.csv raw_data_2018.csv raw_data_2019.csv processed_data Now,wecanchecktoseeifthefileraw_data_2019.csvisinthefolder.Asyoucansee,itis. Let’sbreakdownourcode.Onthefirstline,weimporttheosmodule,whichweneedtodoinordertoaccesstheos.listdir()function.Then,wedeclareaPythonvariablecalledpath,whichstoresthenameofthepathwhosecontentswewanttoretrieve. Onthenextline,weusetheos.listdir()methodtogetalistofthefilesandfoldersinthe/home/data_analysis/netflixdirectory.Finally,wecreateaPythonforloop.Thisloopiteratesthrougheveryiteminthelistproducedbyos.listdir().WeprintoutthenameofeachfiletotheconsoleusingaPythonprint()statement. »MORE: Python:ReturnMultipleValuesfromaFunctionThe/home/data_analysis/netflixdirectorycontainedsixfilesandonedirectory.Thedirectoryiscalledprocessed_dataandisdistinguishablefromtheotherfilesbecauseitdoesnothaveanextension. Pythonos.walk() Theos.walk()functionretrievesalistoffilescontainedwithinatree.Themethoditeratesovereachdirectoryinatree.Then,os.walk()returnsthenameofeveryfileandfolderwithinadirectoryandanyofitssubdirectories. Thesyntaxfortheos.walk()methodisasfollows: os.walk(top,topdown,onerror,followlinks) Theos.walk()methodacceptsfourparameters: topisthetopdirectorywhosecomponentfileandfoldernamesyouwanttoretrieve(required)topdown,whensettoTrue,specifiesthatdirectoriesshouldbescannedfromthetopdown.IfthisvalueissettoFalse,directorieswillbescannedfromthebottomup(optional)onerrorprovidesanerrorhandlerifanerrorisencountered(optional)followlinks,ifsettoTrue,visitsfoldersreferencedbysystemlinks(optional) Wearegoingtofocusonthefirsttwoparameterssinceonerrorandfollowlinksaremoreadvancedandarenotascommonlyused. os.walk()PythonExample Let’ssaythatwewanttoretrievethenamesofallfilesinthe/home/data_analysis/netflixdirectory.Wealsowanttofindoutwhat’senclosedwithinallsubdirectoriesinthatfolder. Aswediscussedabove,thenetflixdirectorycontainsonefolder:processed_data.Wecouldusethefollowingcodetoretrievethenamesofallfilesinthe/home/data_analysis/netflixdirectoryanditssubdirectories: importos path='/home/data_analysis/netflix' forroot,directories,filesinos.walk(path,topdown=False): fornameinfiles: print(os.path.join(root,name)) fornameindirectories: print(os.path.join(root,name)) Here’stheoutputfromourcode: "CareerKarmaenteredmylifewhenIneededitmostandquicklyhelpedmematchwithabootcamp.Twomonthsaftergraduating,Ifoundmydreamjobthatalignedwithmyvaluesandgoalsinlife!" Venus,SoftwareEngineeratRockbot FindYourBootcampMatch /home/data_analysis/netflix/README.md /home/data_analysis/netflix/app.py /home/data_analysis/netflix/raw_data_2016.csv /home/data_analysis/netflix/raw_data_2017.csv /home/data_analysis/netflix/raw_data_2018.csv /home/data_analysis/netflix/raw_data_2019.csv /home/data_analysis/netflix/processed_data /home/data_analysis/netflix/processed_data/final.csv Weimporttheosmodulefromwhichwereferencetheos.walk()andos.path.join()methodslaterinourcode.Then,wedeclareavariablecalledpath,whichstoresthepathwhosefilenameswewanttodiscover. »MORE: LearnPythonforEngineers:LearningResources,Libraries,andBasicSteps Wethencreateaforloopthatusesos.walk()toretrievealistofallfilesandfoldersinthepathdirectory.Thatloopiteratesthroughthefilesandfoldersthatos.walk()returns.It’sworthnotingthatwespecifythetopdown=Falseparameterintheos.walk()method,whichtellsourcodetoconductatop-downsearch. Ourforloopiteratesthrougheachfileanddirectorydiscoveredbytheos.walk()methodusingadditionalforloops.Weprintoutthefilesinos.walk()totheconsole. Inourcodeabove,hereareourforloops: forroot,directories,filesinos.walk(path): fornameinfiles: print(os.path.join(root,name)) fornameindirectories: print(os.path.join(root,name)) Then,ourprogramusesos.path.join()tojointogethertherootfolderofeachfile(i.e./home/data_analysis/netflix)andthenameofthefile(i.e.raw_datra_2019.csv).Therootfolderreferstothedirectorypathinwhichafileexists. Conclusion YoucanusethePythonlistdir()methodtodothis.Youcanalsousethewalk()method,whichlistseverythinginadirectory,includinganythingwithinsubdirectories. Thisguideexplored,providingexamples,howtousetheos.listdir()andos.walk()methodstolistfilesandfoldersinadirectoryinPython.NowyouhavetheskillsyouneedtolistfilesinadirectoryinPythonlikeanexpert! TolearnmoreaboutcodinginPython,readourfullHowtoLearnPythonguide. 1Ratings Aboutus:CareerKarmaisaplatformdesignedtohelpjobseekersfind,research,andconnectwithjobtrainingprogramstoadvancetheircareers.LearnabouttheCKpublication. What'sNext? Wanttotakeaction? Getmatchedwithtopbootcamps Wanttodivedeeper? Askaquestiontoourcommunity Wanttoexploretechcareers? Takeourcareersquiz JamesGallagher JamesGallagherisaself-taughtprogrammerandthetechnicalcontentmanageratCareerKarma.HehasexperienceinrangeofprogramminglanguagesandextensiveexpertiseinPython,HTML,CSS,andJavaScript.Jameshaswrittenhundredsofprogrammingtutorials,andhefrequentlycontributestopublicationslikeCodecademy,Treehouse,Repl.it,Afrotech,andothers.He...readmore ReadmorebyJamesGallagher ShareThis PreviousArticlePythonCeilandFloor:AStep-By-StepGuide NextArticlePythonConcatenateStrings:Step-By-StepGuide Nov19,2020 Comments(0) LeaveaReplyCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*YourCommentName* Email* Website Δ ApplytotoptechtrainingprogramsinoneclickGetMatched RelatedArticles PythonTutorials PythonTutorials PythonTutorials PythonTutorials Manycareersintechpayover$100,000peryear.WithhelpfromCareerKarma,youcanfindatrainingprogramthatmeetsyourneedsandwillsetyouupforalong-term,well-paidcareerintech. Selectyourinterest: SoftwareEngineering Design DataScience DataAnalytics Sales UXDesign CyberSecurity DigitalMarketing FirstName LastName Email PhoneNumber GETMATCHED Findtherightbootcampforyou BycontinuingyouagreetoourTermsofServiceandPrivacyPolicy,andyouconsenttoreceiveoffersandopportunitiesfromCareerKarmabytelephone,textmessage,andemail. X Findatop-ratedtrainingprogram Findatop-ratedtrainingprogram



請為這篇文章評分?