Python - List Files in a Directory - ItsMyCode
文章推薦指數: 80 %
In Python we can List Files in a Directory using the os module which has built-in methods like os.walk(), os.listdir(), and we can use glob module to list ... Home»Python»Python–ListFilesinaDirectoryTotal0Shares000000000TableofContents HideMethod1:Usingos.listdir()methodMethod2:Usingos.walk()methodMethod3:Usingos.scan()methodMethod4:UsingglobmoduleThereareseveralmodulesavailableinPythontolistfilesinadirectoryorfolder.Someofthepopularoneswecanuseareos,pathlib,glob,fnmatch,etc.Thistutorialwilllookatthemostpopularwaytolistallthefilesinadirectory.Method1:Usingos.listdir()methodWecanuseos.listdir()togetallthefilesanddirectoriesinthespecifiedpath.Syntax–os.listdir(path)Ittakesapathasaparameterandreturnsalistofallfilesanddirectoriesinaspecifiedpath.#importOSmodule importos #Listallthefilesanddirectories path="C:\Projects\Tryouts" dir_list=os.listdir(path) print("Filesanddirectoriesin'",path,"':") #printsallfiles print(dir_list) OutputFilesanddirectoriesin'C:\Projects\Tryouts': ['calc.py','etc','listindexerror.py','main.py','PythonTutorial.py','PythonTutorial.txt','test','test-Copy','__pycache__']Method2:Usingos.walk()methodTheosmoduleprovidesmanyfunctionstointeractwithoperatingsystemfeatures,andonesuchmethodisos.walk(),whichgeneratesthefilesandfoldersinadirectorytree.Itcantraversethetreeeithertop-downorbottom-upsearch,andbydefault,itsetsastop-downsearch.Theos.walk()alsohelpstoretrievethefilesandfolderintheabsolutepath.#importOSmodule importos #Listallthefilesanddirectories path="C:\Projects\Tryouts" for(root,directories,files)inos.walk(path,topdown=False): fornameinfiles: print(os.path.join(root,name)) fornameindirectories: print(os.path.join(root,name))OutputC:\Projects\Tryouts\etc\password.txt C:\Projects\Tryouts\test\python.txt C:\Projects\Tryouts\test-Copy\python.txt C:\Projects\Tryouts\__pycache__\calc.cpython-39.pyc C:\Projects\Tryouts\calc.py C:\Projects\Tryouts\listindexerror.py C:\Projects\Tryouts\main.py C:\Projects\Tryouts\PythonTutorial.py C:\Projects\Tryouts\PythonTutorial.txt C:\Projects\Tryouts\etc C:\Projects\Tryouts\test C:\Projects\Tryouts\test-Copy C:\Projects\Tryouts\__pycache__Method3:Usingos.scan()methodos.scan()methodisavailableinPython3.5andabove.scandir()acceptseitherabytesorstrobjectforthepathparameterandreturns theDirEntry.nameandDirEntry.pathattributeswiththesametypeasthepath.Syntax: os.scandir(path=‘.’)#importOSmodule importos #Listallthefilesanddirectories path="C:\Projects\Tryouts" data=os.scandir() foritemindata: ifitem.is_dir()oritem.is_file(): print(item.name)Outputcalc.py etc listindexerror.py main.py PythonTutorial.py PythonTutorial.txt test test-Copy __pycache__Method4:UsingglobmoduleTheglobmodulehelpsyouretrievethefiles/pathmatchingaspecifiedpatternastheglobsupportsthewildcardsearch.Wecangetbothfilesandfoldersusingtheglobmodule.#importOSmodule importglob #Listallthefilesanddirectories path="C:\Projects\Tryouts\*" forfile_nameinglob.iglob(path,recursive=True): print(file_name)C:\Projects\Tryouts\calc.py C:\Projects\Tryouts\etc C:\Projects\Tryouts\listindexerror.py C:\Projects\Tryouts\main.py C:\Projects\Tryouts\PythonTutorial.py C:\Projects\Tryouts\PythonTutorial.txt C:\Projects\Tryouts\test C:\Projects\Tryouts\test-Copy C:\Projects\Tryouts\__pycache__Wecanalsoprintthefilenamesrecursivelyusingtheiglob()method.Allyouneedtodoissettherecursiveparameterastrue.Belowtheexample,weuseiglob()methodwithrecursivesettotrueandsearchingwithaspecificpatterntogetallthe.pyfiles#importOSmodule importglob #Listallthefilesanddirectories path="C:\Projects\Tryouts\*.py" forfile_nameinglob.iglob(path,recursive=True): print(file_name)OutputC:\Projects\Tryouts\calc.py C:\Projects\Tryouts\listindexerror.py C:\Projects\Tryouts\main.py C:\Projects\Tryouts\PythonTutorial.pyreportthisadTotal0SharesShare 0Tweet 0Share 0Share 0Share 0SrinivasBlogger,Traveller,InvestorandTechnologist.RelatedTagsglob,os,os.listdir(),os.scan(),os.walkLeaveaReplyCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*Comment*Name*Email*WebsiteSavemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. ΔViewComments(0)SignUpforOurNewslettersGetnotifiedofthebestdealsonourWordPressthemes. SubscribeBycheckingthisbox,youconfirmthatyouhavereadandareagreeingtoourtermsofuseregardingthestorageofthedatasubmittedthroughthisform.YouMayAlsoLikeHowToSQL2minutereadEveryonewouldhavecomeacrossascenariowherethereisaneedtofindtheSizeofthetableinMSSQL.Therearemultiplewaystofindsizeoftable…ViewPostPython2minutereadTableofContentsHideTheProblem:IndexError:listindexoutofrangeThesolutiontoIndexerror:listindexoutofrangeSolution1–Usinglen()functionSolution2–Usingforloop…ViewPostPython1minutereadTableofContentsHidecapitalize()Syntaxcapitalize()ParameterReturnValuefromcapitalize()Example: CapitalizeastringinPythonPythonstringcapitalize()methodwillconvertthefirstletterinastringtouppercaseandkeep…ViewPostPython1minutereadTableofContentsHidetitle()Syntaxtitle()Parameterstitle()ReturnValueExample1:HowPythontitle()works?Example2:title()methodincaseofnumberandapostrophesThePythonStringtitle()methodisa…ViewPostPython3minutereadTableofContentsHideDifferencebetweenstrip()vsrstrip()vslstrip()strip()Exampleofstrip()function rstrip()Exampleofrstrip()function lstrip()Exampleoflstrip()function Pythonprovidesthreemethodstotrimthe…ViewPostPython3minutereadTableofContentsHideJSONPathLibraryinPythonInstallingjsonpath-ngModuleJsonpathoperators:ParsingaSimpleJSONDatausingJSONPathParsingaJsonArrayusingJSONPathExpressionJSONPathisanexpressionlanguagethatis…ViewPostTrendingTopics 1HowtogetcolumnnamesinPandasDataframeApril24,2022 2ConvertDateTimetoUnixtimestampinPythonApril23,2022 3PythonListpop()April17,2022reportthisadFeaturedCategoriesHowToViewPostsJavascriptViewPostsPythonreportthisad ViewPostsxx
延伸文章資訊
- 1Python, how to list files and folders in a directory - Flavio Copes
To list files in a directory, you can use the listdir() method that is provided by the os built-i...
- 2Python List Files in a Directory [5 Ways] - PYnative
os.listdir('dir_path') : Return the list of files and directories present in a specified director...
- 3How to read multiple text files from folder in Python? - GeeksforGeeks
- 4How To List Files In Directory Python- Detailed Guide - Stack ...
- 5Python: List Files in a Directory - Stack Abuse
The command ls -p . ... lists directory files for the current directory, and adds the delimiter /...