Python - List Files in a Directory - GeeksforGeeks

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

Python – List Files in a Directory ; os.listdir() method gets the list of all files and directories in a specified directory. By default, it is ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryMust-DoCodingQuestionsExploreMoreForStudentsLIVECompetitiveProgrammingDataStructureswithC++DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsPracticeDS&Algo.MustDoQuestionsDSATopic-wiseDSACompany-wiseAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsGeekontheTopCareersInternshipJobsApplyforJobsPostaJobJOB-A-THONEvents ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesPython–ListFilesinaDirectoryPython|os.listdir()methodOSPathmoduleinPythonOSModuleinPythonwithExamplesPython|os.path.join()methodCreateadirectoryinPythonPython:CheckifaFileorDirectoryExistsPython|os.mkdir()methodPython|os.makedirs()methodPython|os.path.exists()methodPython|os.path.isfile()methodPython|os.path.isdir()methodos.walk()inPythonHowtouseGlob()functiontofindfilesrecursivelyinPython?Python:PassingDictionaryasArgumentstoFunctionPython|PassingdictionaryaskeywordargumentsPythonExceptionHandlingPythonTryExceptErrorsandExceptionsinPythonBuilt-inExceptionsinPythonUser-definedExceptionsinPythonwithExamplesNZECerrorinPythonFileHandlinginPythonOpenaFileinPythonHowtoreadfromafileinPythonAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonTableofContentsPython–ListFilesinaDirectoryPython|os.listdir()methodOSPathmoduleinPythonOSModuleinPythonwithExamplesPython|os.path.join()methodCreateadirectoryinPythonPython:CheckifaFileorDirectoryExistsPython|os.mkdir()methodPython|os.makedirs()methodPython|os.path.exists()methodPython|os.path.isfile()methodPython|os.path.isdir()methodos.walk()inPythonHowtouseGlob()functiontofindfilesrecursivelyinPython?Python:PassingDictionaryasArgumentstoFunctionPython|PassingdictionaryaskeywordargumentsPythonExceptionHandlingPythonTryExceptErrorsandExceptionsinPythonBuilt-inExceptionsinPythonUser-definedExceptionsinPythonwithExamplesNZECerrorinPythonFileHandlinginPythonOpenaFileinPythonHowtoreadfromafileinPythonAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonImproveArticle SaveArticle LikeArticle Python–ListFilesinaDirectoryLastUpdated: 03Jun,2021Directoryalsosometimesknownasafolderareunitorganizationalstructureincomputer’sfilesystemforstoringandlocatingfilesormorefolders.PythonnowsupportsanumberofAPIstolistthedirectorycontents.Forinstance,wecanusethePath.iterdir,os.scandir,os.walk,Path.rglob,oros.listdirfunctions. Directoryinuse:gfgMethod1:Osmodule os.listdir()methodgetsthelistofallfilesanddirectoriesinaspecifieddirectory.Bydefault,itisthecurrentdirectory.Syntax:os.listdir(path)Parameters:PathofthedirectoryReturnType:returnsalistofallfilesanddirectoriesinthespecifiedpathExample1:Python#importOSmoduleimportos #Getthelistofallfilesanddirectoriespath="C://Users//Vanshi//Desktop//gfg"dir_list=os.listdir(path) print("Filesanddirectoriesin'",path,"':") #printsallfilesprint(dir_list)Output:   Program2:Togetonlytxtfiles.Python3#importOSimportos forxinos.listdir():    ifx.endswith(".txt"):        #PrintsonlytextfilepresentinMyFolder        print(x)  Output:  OS.walk()generatesfilenamesinadirectorytree.  Python3#importOSmoduleimportos #Thisismypathpath="C://Users//Vanshi//Desktop//gfg" #tostorefilesinalistlist=[] #dirs=directoriesfor(root,dirs,file)inos.walk(path):    forfinfile:        if'.txt'inf:            print(f)Output:   os.scandir()issupportedforPython3.5andgreater. Syntax:os.scandir(path=‘.’)ReturnType:returnsaniteratorofos.DirEntryobject.Example:Python3#importOSmoduleimportos #Thisismypathpath="C://Users//Vanshi//Desktop//gfg" #Scanthedirectoryandget#aniteratorofos.DirEntryobjects#correspondingtoentriesinit#usingos.scandir()methodobj=os.scandir() #Listallfilesanddirectoriesinthespecifiedpathprint("FilesandDirectoriesin'%s':"%path)forentryinobj:    ifentry.is_dir()orentry.is_file():        print(entry.name)Output:Method2:UsingglobTheglobmoduleisusedtoretrievefiles/pathnamesmatchingaspecifiedpattern. glob()methodWithglob,wecanusewildcards(“*,?,[ranges])tomakepathretrievalmoresimpleandconvenient.Python3importglob #Thisismypathpath="C:\\Users\\Vanshi\\Desktop\\gfg" #Using'*'patternprint('\nNamedwithwildcard*:')forfilesinglob.glob(path+'*'):    print(files) #Using'?'patternprint('\nNamedwithwildcard?:')forfilesinglob.glob(path+'?.txt'):    print(files)  #Using[0-9]patternprint('\nNamedwithwildcardranges:')forfilesinglob.glob(path+'/*[0-9].*'):    print(files)Output: iglob()methodcanbeusedtoprintfilenamesrecursivelyiftherecursiveparameterissettoTrue.Syntax: glob.glob(pathname,*,recursive=False)Example:Python3importglob #Thisismypathpath="C:\\Users\\Vanshi\\Desktop\\gfg**\\*.txt"   #Itreturnsaniteratorwhichwill#beprintedsimultaneously.print("\nUsingglob.iglob()") #PrintsalltypesoftxtfilespresentinaPathforfileinglob.iglob(path,recursive=True):    print(file)Output:MyPersonalNotes arrow_drop_upSave LikeNext Python|os.listdir()methodRecommendedArticlesPage:10,Dec2027,Jul2123,Aug2129,Aug2117,Jun2128,Nov1922,Jan2116,Feb2104,May2113,May2121,Jun2116,Apr2127,May2128,May2122,Sep2013,Jan2124,Jan1925,Nov1925,Nov1926,Nov1926,Nov1926,Nov1927,Nov1927,Nov19ArticleContributedBy:aksrathod07@aksrathod07VotefordifficultyEasy Normal Medium Hard ExpertImprovedBy:sooda367ArticleTags:python-file-handlingPythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinPythonPythonDictionaryReadafilelinebylineinPythonEnumerate()inPythonHowtoInstallPIPonWindows?IterateoveralistinPythonMorerelatedarticlesinPythonDifferentwaystocreatePandasDataframePythonString|replace()CreateaPandasDataFramefromListsPythonprogramtoconvertalisttostringReadingandWritingtotextfilesinPython× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?