Python Directory Listing - AskPython
文章推薦指數: 80 %
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
延伸文章資訊
- 18 Examples to Implement os.listdir() in Python
Example 7: Python listdir absolute path
- 2How To List Files In Directory Python- Detailed Guide - Stack ...
To list the files with a full path, you can use the os.path ...
- 3Python 列出目錄中所有檔案教學:os.listdir 與os.walk - GT Wang
os.listdir 可以取得指定目錄中所有的檔案與子目錄名稱,以下是一個簡單 ... 的絕對路徑 fullpath = join(mypath, f) # 判斷fullpath 是檔案還是目錄...
- 4Python | os.listdir() method - GeeksforGeeks
os.listdir() method in python is used to get the list of all files and directories in the specifi...
- 5os.listdir with full path Code Example
Python answers related to “os.listdir with full path”. how to get all folders on path in python ·...