Python | os.path.dirname() method - GeeksforGeeks
文章推薦指數: 80 %
os.path.dirname() method in Python is used to get the directory name from the specified path. Syntax: os.path.dirname( ... 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|os.path.dirname()methodPython|os.path.join()methodOSPathmoduleinPythonOSModuleinPythonwithExamplesCreateadirectoryinPythonPython: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?Python:PassingDictionaryasArgumentstoFunctionPython|PassingdictionaryaskeywordargumentsPythonExceptionHandlingPythonTryExceptErrorsandExceptionsinPythonBuilt-inExceptionsinPythonUser-definedExceptionsinPythonwithExamplesNZECerrorinPythonFileHandlinginPythonOpenaFileinPythonHowtoreadfromafileinPythonAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonTableofContentsPython|os.path.dirname()methodPython|os.path.join()methodOSPathmoduleinPythonOSModuleinPythonwithExamplesCreateadirectoryinPythonPython: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?Python:PassingDictionaryasArgumentstoFunctionPython|PassingdictionaryaskeywordargumentsPythonExceptionHandlingPythonTryExceptErrorsandExceptionsinPythonBuilt-inExceptionsinPythonUser-definedExceptionsinPythonwithExamplesNZECerrorinPythonFileHandlinginPythonOpenaFileinPythonHowtoreadfromafileinPythonAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonImproveArticle SaveArticle LikeArticle Python|os.path.dirname()methodLastUpdated: 26Aug,2019OSmoduleinPythonprovidesfunctionsforinteractingwiththeoperatingsystem.OScomesunderPython’sstandardutilitymodules.Thismoduleprovidesaportablewayofusingoperatingsystemdependentfunctionality.os.pathmoduleissubmoduleofOSmoduleinPythonusedforcommonpathnamemanipulation.os.path.dirname()methodinPythonisusedtogetthedirectorynamefromthespecifiedpath.Syntax:os.path.dirname(path)Parameter:path:Apath-likeobjectrepresentingafilesystempath.ReturnType:Thismethodreturnsastringvaluewhichrepresentsthedirectorynamefromthespecifiedpath.Code:Useofos.path.dirname()method#Pythonprogramtoexplainos.path.dirname()method #importingos.pathmodule importos.path #Pathpath='/home/User/Documents' #Getthedirectoryname #fromthespecifiedpathdirname=os.path.dirname(path) #Printthedirectoryname print(dirname) #Pathpath='/home/User/Documents/file.txt' #Getthedirectoryname #fromthespecifiedpathdirname=os.path.dirname(path) #Printthedirectoryname print(dirname) #Pathpath='file.txt' #Getthedirectoryname #fromthespecifiedpathdirname=os.path.dirname(path) #Printthedirectoryname print(dirname) #Intheabovespecifiedpath #doesnotcontainsany#directoryso, #ItwillprintNothing Output: /home/User /home/User/Documents Reference:https://docs.python.org/3/library/os.path.htmlMyPersonalNotes arrow_drop_upSave LikeNext Python|os.path.join()methodRecommendedArticlesPage: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@ihritikVotefordifficultyEasy Normal Medium Hard ExpertArticleTags:PythonOS-path-modulepython-os-modulePythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinPythonPythonDictionaryReadafilelinebylineinPythonEnumerate()inPythonHowtoInstallPIPonWindows?IterateoveralistinPythonMorerelatedarticlesinPythonDifferentwaystocreatePandasDataframePythonString|replace()CreateaPandasDataFramefromListsPythonprogramtoconvertalisttostringReadingandWritingtotextfilesinPython× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1Python 獲取文件路徑及文件目錄( __file__ 的使用方法) - GitHub
透過問答,了解世界。Python 的世界. Contribute to dokelung/Python-QA development by creating an account on GitHub.
- 2Python 取出目錄的路徑dirname
本篇ShengYu 介紹Python 取出目錄的路徑os.path.dirname() 的用法與範例,並示範在linux、macOS、windows 各平台下的差異。以下範例是在Python 3...
- 3Python:使用os.walk() 遞迴印出資料夾中所有目錄及檔名
短短幾行就能達成我的目的,且python 的程式碼也能在windows 上運作。 以下是能達成我目的的 Python walk.py 原始碼: import os for dirPath, di...
- 4os.path — Common pathname manipulations — Python 3.10 ...
path module is always the path module suitable for the operating system Python is running on, and...
- 5Python 如何得到資料夾下的所有檔案 - Delft Stack
os.listdir 列出了給定資料夾下的所有檔案和資料夾,所以我們需要新增額外的程式碼來只把檔案給提取出來。 Python. pythonCopy import os dirPath = r"...