Python Directory Listing - AskPython

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

If you want to print the absolute path of all the files from your current directory, simply add an os.path.join() to the os.listdir() function! SkiptocontentInthisarticle,we’lllookathowwecanperformPythondirectorylisting.Thiswillallowustolistallthefilesanddirectoriesinthecurrentworkinglocation.Often.wemaywanttoquicklylookatthefilenamesandgetinformationusingPython.Let’slookathowwecandoitquicklyandeasily!1.PythonDirectoryListingUsingos.listdir()ThisisashortandsweetmethodtoperformPythondirectorylisting,fromyourcurrentdirectory!It’sreallyjustoneline.Don’tbelieveme?Here’sanexample.Thisappliestoanyoperatingsystem,whetheritbeWindows/Linux/MacOS.importos print(os.listdir()) ExampleOutput>>>importos >>>os.listdir() ['.bashrc','.git','.nvimrc','.vimrc','.xinitrc','.zshrc','Autumn.jpg','README.md','config'] Thiswillreturnalistofallfilesandnestedfolders,fromyourcurrentdirectory.Ifyouwanttospecifyanexactpath,youcansimplypassitasanargumenttoos.listdir(path)!>>>os.listdir(r'/home/vijay/manjaro-dotfiles') ['.bashrc','.git','.nvimrc','.vimrc','.xinitrc','.zshrc','Autumn.jpg','README.md','config'] Userawstrings(stringsprefixedwithr)whenyou’redealingwithpaths,sinceyouwon’tneedtoescapeanybackslashes(forWindowspaths).2.Useos.path.join()withos.listdir()Ifyouwanttoprinttheabsolutepathofallthefilesfromyourcurrentdirectory,simplyaddanos.path.join()totheos.listdir()function!We’llmakeafunctionforthis,whichsimplygetsthefullpath,andreturnsalistofallsuchnames.importos deflist_full_paths(directory): return[os.path.join(directory,file)forfileinos.listdir(directory)] print(list_full_paths(r'/home/accornition/manjaro-dotfiles')) Output['/home/vijay/manjaro-dotfiles/.bashrc','/home/vijay/manjaro-dotfiles/.git','/home/vijay/manjaro-dotfiles/.nvimrc','/home/vijay/manjaro-dotfiles/.vimrc','/home/vijay/manjaro-dotfiles/.xinitrc','/home/vijay/manjaro-dotfiles/.zshrc','/home/vijay/manjaro-dotfiles/Autumn.jpg','/home/vijay/manjaro-dotfiles/README.md','/home/vijay/manjaro-dotfiles/config'] Indeed,thisgivesustheabsolutepath,fromtherootdirectory!3.PythonDirectoryListingUsingos.walk()Wecanalsousetheos.walk()functiontowalkthroughthedirectorytree.Wecanthenprintthedirectoriesandfilesindividually.fortop,dirs,filesinos.walk(os.getcwd()): print("Printingdirectories...") fordirindirs: print(os.path.join(top,dir)) print("Printingfiles....") forfileinfiles: print(os.path.join(top,file)) OutputPrintingdirectories... /home/vijay/manjaro-dotfiles/config/cmus/home/vijay/manjaro-dotfiles/config/compton/home/vijay/manjaro-dotfiles/config/termitePrintingfiles.... Printingdirectories... Printingfiles..../home/vijay/manjaro-dotfiles/config/cmus/my.themePrintingdirectories... Printingfiles.... /home/vijay/manjaro-dotfiles/config/compton/compton.confPrintingdirectories... Printingfiles.... /home/vijay/manjaro-dotfiles/config/termite/config Youcanuseanyoftheabovethreemethods,dependingonyouruse-casescenario.Thefirstmethodistheeasiestandtherecommendedone,butifyouwantthefullpath,andwanttotravelrecursively,useos.walk().ConclusionInthisarticle,welearnedhowwecouldlistfilesanddirectoriesinPython,usingdifferentmethods.ReferencesStackOverflowquestiononlistingcontentsfromaDirectory Postnavigation←PreviousPostNextPost→ Searchfor: RecentPosts GamStopAPI:WorththeWaitforOpenUse WhydoTradersNeedtoStartLearningPython? ResizethePlotsandSubplotsinMatplotlibUsingfigsize DiagnoseFeverInPython[EasyCLIMethod] DesigningStateMachinesusingPython[AQuickGuide] TkinterCreateOval–AQuickGuide WebTechnologiesUsedintheFrontendofOnlineCasinos SoftwareThatBlocksGamblingSites ProgrammingLanguagesForOnlineCasinoImplementation RegressionSplinesinPython–ABeginnersIntroductionFavoriteSitesJournalDevGoLangDocsVM-HelpLinuxForDevicesMySQLCodeCodeForGeek



請為這篇文章評分?