How to List Files in a Directory Using Python? - AskPython
文章推薦指數: 80 %
files = [f for f in os.listdir(path) if os.path.isfile(f)] ... In the above code snippet, List Comprehension is used to filter out only those items that are ... SkiptocontentInthistutorial,we’recoveringeverythingyouneedtoknowabouthowtolistfilesinadirectoryusingPython.Pythonisageneral-purposelanguage,usedinavarietyoffieldslikeDataScience,MachineLearning,andeveninWebDevelopment.ThereseemstobenorestrictionintheapplicationofPythonLanguage.Therefore,itseemsquitetrivialPythoncanbeusedtolistfilesanddirectoriesinanysystem.TheaimofthisarticleistoilluminatethereaderaboutthewaystolistfilesinasystemusingPython.ListAllFilesinaDirectoryUsingPythonForthepurposeofinteractingwithdirectoriesinasystemusingPython,theoslibraryisused.1.Usingthe‘os’libraryThemethodthatwearegoingtoexerciseforourmotiveislistdir().Asthenamesuggests,itisusedtolistitemsindirectories.#Importingtheoslibrary importos #Thepathforlistingitems path='.' #Thelistofitems files=os.listdir(path) #Looptoprinteachfilenameseparately forfilenameinfiles: print(filename) Output:game_file.py hi-lo_pygame.py Journaldev list_files1.py hi_lo_pygame.mp4 test.py list_files.py my_program.cpp a.out cut.cpp Linuxuserscaneasilymatchtheaboveoutputusingthestandardlscommandontheterminal.ListItemsusing‘ls’commandAswecanseetheoutputsofeachmethodmatches.2.Usingthe‘glob’libraryglobismostlyafilenamepatternmatchinglibrary,butitcanbeusedtolistitemsinthecurrentdirectoryby:#Importingthegloblibrary importglob #Pathtothedirectory path='' #or #path='./' #Extractthelistoffilenames files=glob.glob(path+'*',recursive=False) #Looptoprintthefilenames forfilenameinfiles: print(filename) Output:game_file.py hi-lo_pygame.py Journaldev list_files1.py hi_lo_pygame.mp4 test.py list_files.py my_program.cpp a.out cut.cpp Thewildcardcharacter'*'isusedtomatchalltheitemsinthecurrentdirectory.Sincewewishtodisplaytheitemsofthecurrentdirectory,weneedtoswitchofftherecursivenatureofglob()function.3.ListonlyfilesinthecurrentdirectoryIntheabovemethods,thepythoncodewasreturningalltheitemsinthecurrentdirectoryirrespectiveoftheirnature.Wecanextractonlythefilesusingthepath.isfile()functioninsidetheoslibrary.#Importingtheoslibrary importos #Thepathforlistingitems path='.' #Listofonlyfiles files=[fforfinos.listdir(path)ifos.path.isfile(f)] #Looptoprinteachfilenameseparately forfilenameinfiles: print(filename) Output:game_file.py hi-lo_pygame.py list_files1.py hi_lo_pygame.mp4 test.py list_files.py my_program.cpp a.out cut.cpp Intheabovecodesnippet,ListComprehensionisusedtofilteroutonlythoseitemsthatareactuallyafile.Anotherkeythingtonotehereisthat,theabovecodedoesnotworkforotherdirectoriesasthevariable'f'isnotanabsolutepath,butarelativepathtothecurrentdirectory.ListAllFilesinaDirectoryRecursivelyInordertoprintthefilesinsideadirectoryanditssubdirectories,weneedtotraversethemrecursively.1.Usingthe‘os’libraryWiththehelpofthewalk()method,wecantraverseeachsubdirectorywithinadirectoryonebyone.#Importingtheoslibrary importos #Thepathforlistingitems path='./Documents/' #Listoffilesincompletedirectory file_list=[] """ Looptoextractfilesinsideadirectory path-->Nameofeachdirectory folders-->Listofsubdirectoriesinsidecurrent'path' files-->Listoffilesinsidecurrent'path' """ forpath,folders,filesinos.walk(path): forfileinfiles: file_list.append(os.path.join(path,file)) #Looptoprinteachfilenameseparately forfilenameinfile_list: print(filename) Output:./Documents/game_file.py ./Documents/hi-lo_pygame.py ./Documents/list_files1.py ./Documents/hi_lo_pygame.mp4 ./Documents/test.py ./Documents/list_files.py ./Documents/my_program.cpp ./Documents/a.out ./Documents/cut.cpp ./Documents/Journaldev/mastermind.py ./Documents/Journaldev/blackjack_terminal.py ./Documents/Journaldev/lcm.cpp ./Documents/Journaldev/super.cpp ./Documents/Journaldev/blackjack_pygame.py ./Documents/Journaldev/test.java Theos.walk()methodsimplyfollowseachsubdirectoryandextractsthefilesinatop-downmannerbydefault.Therearethreeiteratorsusedforgoingthroughtheoutputofos.walk()function:path–Thisvariablecontainsthepresentdirectorythefunctionisobservingduringacertainiterationfolders–Thisvariableisalistofdirectoriesinsidethe'path'directory.files–Alistoffilesinsidethe'path'directory.Thejoin()methodisusedtoconcatenatethefilenamewithitsparentdirectory,providinguswiththerelativepathtothefile.2.Usingthe‘glob’librarySimilartotheaboveprocedure,globcanrecursivelyvisiteachdirectoryandextractallitemsandreturnthem.#Importingthegloblibrary importglob #Importingtheoslibrary importos #Pathtothedirectory path='./Documents/' #Extractallthelistofitemsrecursively files=glob.glob(path+'**/*',recursive=True) #Filteronlyfiles files=[fforfinfilesifos.path.isfile(f)] #Looptoprintthefilenames forfilenameinfiles: print(filename) Output:./Documents/game_file.py ./Documents/hi-lo_pygame.py ./Documents/list_files1.py ./Documents/hi_lo_pygame.mp4 ./Documents/test.py ./Documents/list_files.py ./Documents/my_program.cpp ./Documents/a.out ./Documents/cut.cpp ./Documents/Journaldev/mastermind.py ./Documents/Journaldev/blackjack_terminal.py ./Documents/Journaldev/lcm.cpp ./Documents/Journaldev/super.cpp ./Documents/Journaldev/blackjack_pygame.py ./Documents/Journaldev/test.java The'**'symbolusedalongwiththepathvariabletellstheglob()functiontomatchfileswithinanysubdirectory.The'*'tellsthefunctiontomatchwithalltheitemswithinadirectory.Sincewewishtoextractonlythefilesinthecompletedirectory,wefilteroutthefilesusingtheisfile()functionusedbefore.ListAllSubdirectoriesInsideaDirectoryInsteadoflistingfiles,wecanlistallthesubdirectoriespresentinaspecificdirectory.#Importingtheoslibrary importos #Thepathforlistingitems path='./Documents/' #Listoffoldersincompletedirectory folder_list=[] """ Looptoextractfoldersinsideadirectory path-->Nameofeachdirectory folders-->Listofsubdirectoriesinsidecurrent'path' files-->Listoffilesinsidecurrent'path' """ forpath,folders,filesinos.walk(path): forfolderinfolders: folder_list.append(os.path.join(path,folder)) #Looptoprinteachfoldernameseparately forfoldernameinfolder_list: print(foldername) Output:./Documents/Journaldev Theminordifferencebetweenlistingfilesanddirectoriesistheselectionofiteratorduringtheprocessofos.walk()function.Forfiles,weiterateoverthefilesvariable.Here,weloopoverthefoldersvariable.ListFilesinaDirectorywithAbsolutePathOnceweknowhowtolistfilesinadirectory,thendisplayingtheabsolutepathisapieceofcake.Theabspath()methodprovidesuswiththeabsolutepathforafile.#Importingtheoslibrary importos #Thepathforlistingitems path='./Documents/' #Listoffilesincompletedirectory file_list=[] """ Looptoextractfilesinsideadirectory path-->Nameofeachdirectory folders-->Listofsubdirectoriesinsidecurrent'path' files-->Listoffilesinsidecurrent'path' """ forpath,folders,filesinos.walk(path): forfileinfiles: file_list.append(os.path.abspath(os.path.join(path,file))) #Looptoprinteachfilenameseparately forfilenameinfile_list: print(filename) Output:/home/aprataksh/Documents/game_file.py /home/aprataksh/Documents/hi-lo_pygame.py /home/aprataksh/Documents/list_files1.py /home/aprataksh/Documents/hi_lo_pygame.mp4 /home/aprataksh/Documents/test.py /home/aprataksh/Documents/list_files.py /home/aprataksh/Documents/my_program.cpp /home/aprataksh/Documents/a.out /home/aprataksh/Documents/cut.cpp /home/aprataksh/Documents/Journaldev/mastermind.py /home/aprataksh/Documents/Journaldev/blackjack_terminal.py /home/aprataksh/Documents/Journaldev/lcm.cpp /home/aprataksh/Documents/Journaldev/super.cpp /home/aprataksh/Documents/Journaldev/blackjack_pygame.py /home/aprataksh/Documents/Journaldev/test.java Onethingtonotehereisthatabspath()mustbeprovidedwiththerelativepathofthefileandthatisthepurposeofjoin()function.ListFilesinaDirectorybyMatchingPatternsTherearemultiplewaystofilteroutfilenamesmatchingaparticularpattern.Letusgothrougheachofthemonebyone.1.Usingthe‘fnmatch’libraryAsthenamesuggests,fnmatchisafilenamepatternmatchinglibrary.Usingfnmatchwithourstandardfilenameextractinglibraries,wecanfilteroutthosefilesmatchingaspecificpattern.#Importingtheosandfnmatchlibrary importos,fnmatch #Thepathforlistingitems path='./Documents/' #Listoffilesincompletedirectory file_list=[] """ Looptoextractfilescontainingword"file"insideadirectory path-->Nameofeachdirectory folders-->Listofsubdirectoriesinsidecurrent'path' files-->Listoffilesinsidecurrent'path' """ print("Listoffilescontaining\"file\"inthem") forpath,folders,filesinos.walk(path): forfileinfiles: iffnmatch.fnmatch(file,'*file*'): file_list.append(os.path.join(path,file)) #Looptoprinteachfilenameseparately forfilenameinfile_list: print(filename) Output:Listoffilescontaining"file"inthem ./Documents/game_file.py ./Documents/list_files1.py ./Documents/list_files.py Thefnmatch()functiontakesintwoparameters,thefilenamefollowedbythepatterntobematched.Intheabovecode,wearelookingatallthefilescontainingthewordfileinthem.2.Usingthe‘glob’libraryAswementionedbefore,glob'sprimarypurposeisfilenamepatternmatching.#Importingthegloblibrary importglob #Importingtheoslibrary importos #Pathtothedirectory path='./Documents/' #Extractitemscontainingnumbersinname files=glob.glob(path+'**/*[0-9]*.*',recursive=True) #Filteronlyfiles files=[fforfinfilesifos.path.isfile(f)] #Looptoprintthefilenames forfilenameinfiles: print(filename) Output:./Documents/list_files1.py Theabovepatternmatchingregularexpression'**/*[0-9]*.*'canbeexplainedas:'**'–Traverseallsubdirectoriesinsidethepath'/*'–Thefilenamecanstartwithanycharacter'[0-9]'–Containsanumberwithinitsfilename'*.*'–Thefilenamecanendwithanycharacterandcanhaveanyextension3.Usingthe‘pathlib’librarypathlibfollowsanobject-orientedwayofinteractingwiththefilesystem.Therglob()functioninsidethelibrarycanbeusedtorecursivelyextractlistoffilesthroughacertainPathobject.Theselistoffilescanbefilteredusingapatternwithintherglob()function.#Importingthepathliblibrary importpathlib #CreatingaPathobject path=pathlib.Path('./Documents/') #Extractingalistoffilesstartingwith'm' files=path.rglob('m*') #Looptoprintthefilesseparately forfileinfiles: print(file) Output:Documents/my_program.cpp Documents/Journaldev/mastermind.py Theabovecodesnippetisusedtolistallthefilesstartingwiththeletter'm'.ListFilesinaDirectorywithaSpecificExtensionListingfileswithaspecificextensioninPythonissomewhatsimilartopatternmatching.Forthispurpose,weneedtocreateapatternwithrespecttothefileextension.#Importingtheosandfnmatchlibrary importos,fnmatch #Thepathforlistingitems path='./Documents/' #Listtostorefilenames file_list=[] """ Looptoextractpythonfiles path-->Nameofeachdirectory folders-->Listofsubdirectoriesinsidecurrent'path' files-->Listoffilesinsidecurrent'path' """ print("Listofpythonfilesinthedirectory:") forpath,folders,filesinos.walk(path): forfileinfiles: iffnmatch.fnmatch(file,'*.py'): file_list.append(os.path.join(path,file)) #Looptoprinteachfilenameseparately forfilenameinfile_list: print(filename) Output:Listofpythonfilesinthedirectory: ./Documents/game_file.py ./Documents/hi-lo_pygame.py ./Documents/list_files1.py ./Documents/test.py ./Documents/list_files.py ./Documents/Journaldev/mastermind.py ./Documents/Journaldev/blackjack_terminal.py ./Documents/Journaldev/blackjack_pygame.py Thefnmatch()functionfiltersoutthosefilesendingwith'.py',thatispythonfiles.Ifwewanttoextractfileswithdifferentextensions,thenwehavetoalterthispartofthecode.Forexample,inordertofetchonlyC++files,'.cpp'mustbeused.ThissumsupthewaystofetchlistoffilesinadirectoryusingPython.ConclusionTherecanbemultiplewaystosolveanyproblemathand,andthemostconvenientoneisnotalwaystheanswer.Withrespecttothisarticle,aPythonprogrammermustbeawareofeverywaywecanlistfilesinadirectory.Wehopethisarticlewaseasytofollow.Feelfreetocommentbelowforanyqueriesorsuggestions. Postnavigation←PreviousPostNextPost→ Searchfor: RecentPosts GamStopAPI:WorththeWaitforOpenUse WhydoTradersNeedtoStartLearningPython? ResizethePlotsandSubplotsinMatplotlibUsingfigsize DiagnoseFeverInPython[EasyCLIMethod] DesigningStateMachinesusingPython[AQuickGuide] TkinterCreateOval–AQuickGuide WebTechnologiesUsedintheFrontendofOnlineCasinos SoftwareThatBlocksGamblingSites ProgrammingLanguagesForOnlineCasinoImplementation RegressionSplinesinPython–ABeginnersIntroductionFavoriteSitesJournalDevGoLangDocsVM-HelpLinuxForDevicesMySQLCodeCodeForGeek
延伸文章資訊
- 1Python: Get list of files in directory sorted by size - thisPointer
- 2Get a filtered list of files in a directory - python - Stack Overflow
If there is no built-in method for this, I am currently thinking of writing a for loop to iterate...
- 3Get a filtered list of files in a directory - Python - stackoverflow中文 ...
If there is no built-in method for this, I am currently thinking of writing a for loop to iterate...
- 4How To List Files In Directory Python- Detailed Guide - Stack ...
os.listdir() lists all the files and folders in the directory. ... filter only the file type entr...
- 5How to filter file types in a directory in Python - Adam Smith
Use fnmatch.filter() and os.listdir(). Filtering files by type returns a list of all files in a d...