Python | os.listdir() method - GeeksforGeeks

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

os.listdir() method in python is used to get the list of all files and directories in the specified directory. 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:CheckifaFileorDirectoryExistsPython|os.mkdir()methodPython|os.makedirs()methodPython|os.path.exists()methodPython|os.path.isfile()methodPython|os.path.isdir()methodPython|os.listdir()methodos.walk()inPythonHowtouseGlob()functiontofindfilesrecursivelyinPython?OSPathmoduleinPythonOSModuleinPythonwithExamplesPython|os.path.join()methodCreateadirectoryinPythonAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonPythonprogramtoconvertalisttostringReadafilelinebylineinPythonIterateoveralistinPythonReadingandWritingtotextfilesinPythonPythonDictionaryPythonString|replace()Enumerate()inPythonsum()functioninPythonPrintlistsinPython(4DifferentWays)DifferentwaystocreatePandasDataframeisupper(),islower(),lower(),upper()inPythonandtheirapplicationsPython|GetalistasinputfromuserTableofContentsPython:CheckifaFileorDirectoryExistsPython|os.mkdir()methodPython|os.makedirs()methodPython|os.path.exists()methodPython|os.path.isfile()methodPython|os.path.isdir()methodPython|os.listdir()methodos.walk()inPythonHowtouseGlob()functiontofindfilesrecursivelyinPython?OSPathmoduleinPythonOSModuleinPythonwithExamplesPython|os.path.join()methodCreateadirectoryinPythonAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonPythonprogramtoconvertalisttostringReadafilelinebylineinPythonIterateoveralistinPythonReadingandWritingtotextfilesinPythonPythonDictionaryPythonString|replace()Enumerate()inPythonsum()functioninPythonPrintlistsinPython(4DifferentWays)DifferentwaystocreatePandasDataframeisupper(),islower(),lower(),upper()inPythonandtheirapplicationsPython|GetalistasinputfromuserImproveArticle SaveArticle LikeArticle Python|os.listdir()methodDifficultyLevel: BasicLastUpdated: 20May,2019os.listdir()methodinpythonisusedtogetthelistofallfilesanddirectoriesinthespecifieddirectory.Ifwedon’tspecifyanydirectory,thenlistoffilesanddirectoriesinthecurrentworkingdirectorywillbereturned.Syntax:os.listdir(path)Parameters:path(optional):pathofthedirectoryReturnType:Thismethodreturnsthelistofallfilesanddirectoriesinthespecifiedpath.Thereturntypeofthismethodislist.Code#1:useofos.listdir()method#Pythonprogramtoexplainos.listdir()method     #importingosmodule importos  #Getthelistofallfilesanddirectories#intherootdirectorypath="/"dir_list=os.listdir(path)  print("Filesanddirectoriesin'",path,"':")   #printthelistprint(dir_list)Output: Filesanddirectoriesin'/': ['sys','run','tmp','boot','mnt','dev','proc','var','bin','lib64','usr', 'lib','srv','home','etc','opt','sbin','media']  Code#2:useofos.listdir()method#Pythonprogramtoexplainos.listdir()method     #importingosmodule importos  #Getthepathofcurrentworkingdirectorypath=os.getcwd()  #Getthelistofallfilesanddirectories#incurrentworkingdirectorydir_list=os.listdir(path)    print("Filesanddirectoriesin'",path,"':") #printthelistprint(dir_list)Output: Filesanddirectoriesin'/home/ihritik': ['.rstudio-desktop','.gnome','.ipython','.cache','.config','.ssh','Public', 'Desktop','.pki','R','.bash_history','.Rhistory','.oracle_jre_usage','Music', '.ICEauthority','Documents','examples.desktop','.swipl-dir-history','.local', '.gnupg','.profile','Pictures','.keras','.viminfo','.thunderbird','Templates', '.bashrc','.bash_logout','.sudo_as_admin_successful','Videos','images', 'tf_wx_model','Downloads','.mozilla','geeksforgeeks']  Code#3:omittingpathparameter#Pythonprogramtoexplainos.listdir()method    #importingosmodule importos    #Ifwedonotspecifyanypath#os.listdir()methodwillreturn#thelistofallfilesanddirectories#incurrentworkingdirectory  dir_list=os.listdir()  print("Filesanddirectoriesin currentworkingdirectory:")   #printthelistprint(dir_list)Output: Filesanddirectoriesincurrentworkingdirectory: ['.rstudio-desktop','.gnome','.ipython','.cache','.config','.ssh','Public', 'Desktop','.pki','R','.bash_history','.Rhistory','.oracle_jre_usage','Music', '.ICEauthority','Documents','examples.desktop','.swipl-dir-history','.local', '.gnupg','.profile','Pictures','.keras','.viminfo','.thunderbird','Templates', '.bashrc','.bash_logout','.sudo_as_admin_successful','Videos','images', 'tf_wx_model','Downloads','.mozilla','geeksforgeeks'] AswecanseetheoutputofCode#2andCode#3aresame.Soifweomitthepathparameteros.listdir()methodwillreturnthelistofallfilesanddirectoriesinthecurrentworkingdirectory.MyPersonalNotes arrow_drop_upSave LikePreviousPython|os.path.isdir()methodNext os.walk()inPythonRecommendedArticlesPage:11,May1728,Apr2014,Jul1613,Dec1603,May1709,May1721,Aug1921,Aug1921,Aug1921,Jun1921,Jun1903,Oct1812,Dec1804,Feb2010,Jul1903,Oct1812,Oct1716,Nov1717,Nov1720,Nov1720,Nov1723,Nov1713,Dec1706,Dec19ArticleContributedBy:ihritik@ihritikVotefordifficultyCurrentdifficulty: BasicEasy Normal Medium Hard ExpertArticleTags:python-os-modulePythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinPythonHowtoInstallPIPonWindows?CreateaPandasDataFramefromLists*argsand**kwargsinPythonHowtodroponeormultiplecolumnsinPandasDataframeHowToConvertPythonDictionaryToJSON?MorerelatedarticlesinPythonConvertintegertostringinPythonCheckifelementexistsinlistinPythonGraphPlottinginPython|Set1DefaultdictinPythonPython|Getuniquevaluesfromalist× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?