OS Module in Python with Examples - GeeksforGeeks
文章推薦指數: 80 %
The OS module in Python provides functions for interacting with the operating system. OS comes under Python's standard utility modules.
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
▲RelatedArticlesIntroductionPythonProgrammingLanguagePythonLanguageIntroductionPythonLanguageadvantagesandapplicationsDownloadandInstallPython3LatestVersionPython3basicsPythonKeywordsNamespacesandScopeinPythonStatement,IndentationandCommentinPythonHowtoassignvaluestovariablesinPythonandotherlanguagesInput/OutputTakinginputinPythonTakinginputfromconsoleinPythonTakingmultipleinputsfromuserinPythonPython|Outputusingprint()functionHowtoprintwithoutnewlineinPython?Pythonendparameterinprint()Python|sepparameterinprint()Python|OutputFormattingOperatorsPythonOperatorsTernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1OperatorFunctionsinPython|Set2Differencebetween==andisoperatorinPythonPythonMembershipandIdentityOperatorsDataTypesPython|Set3(Strings,Lists,Tuples,Iterations)PythonStringPythonListsPythonTuplesPythonSetsPythonDictionaryPythonArraysControlFlowPythonifelseChainingcomparisonoperatorsinPythonPythonForLoopsPythonWhileLoopPythonbreakstatementPythonContinueStatementPythonpassStatementLoopingTechniquesinPythonFunctionsPythonFunctions*argsand**kwargsinPythonWhentouseyieldinsteadofreturninPython?GeneratorsinPythonPythonlambdaGlobalandLocalVariablesinPythonGlobalkeywordinPythonFirstClassfunctionsinPythonPythonClosuresDecoratorsinPythonDecoratorswithparametersinPythonMemoizationusingdecoratorsinPythonPythonOOPPythonClassesandObjectsConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonClassorStaticVariablesinPythonClassmethodvsStaticmethodinPythonExceptionHandlingPythonExceptionHandlingPythonTryExceptErrorsandExceptionsinPythonBuilt-inExceptionsinPythonUser-definedExceptionsinPythonwithExamplesNZECerrorinPythonFilehandlingFileHandlinginPythonOpenaFileinPythonHowtoreadfromafileinPythonWritingtofileinPythonPythonappendtoafilePythonRegexRegularExpressioninPythonwithExamples|Set1RegularExpressionsinPython–Set2(Search,MatchandFindAll)PythonRegex:re.search()VSre.findall()VerboseinPythonRegexPasswordvalidationinPythonPythonCollectionsPythonCollectionsModuleCountersinPython|Set1(InitializationandUpdation)OrderedDictinPythonDefaultdictinPythonChainMapinPythonNamedtupleinPythonDequeinPythonHeapqueue(orheapq)inPythonCollections.UserDictinPythonCollections.UserListinPythonCollections.UserStringinPythonPythonAdvanceOSModuleinPythonwithExamplesFunctionalProgramminginPythonMetaprogrammingwithMetaclassesinPythonAbstractClassesinPythonMultithreadinginPython|Set1MultithreadinginPython|Set2(Synchronization)MultiprocessinginPython|Set1(Introduction)MultiprocessinginPython|Set2(Communicationbetweenprocesses)SocketProgramminginPythonSocketProgrammingwithMulti-threadinginPythonPythonNumPyNumPyTutorialPythonNumpyNumpy|ndarrayNumpy|ArrayCreationNumpy|IndexingBasicSlicingandAdvancedIndexinginNumPyPythonNumpy|DataTypeObjectsNumpy|IteratingOverArrayNumpy|BinaryOperationsNumpy|MathematicalFunctionNumpy|StringOperationsNumpy|LinearAlgebraNumpy|Sorting,SearchingandCountingRandomsamplinginnumpy|randint()functionRandomsamplinginnumpy|random_sample()functionRandomsamplinginnumpy|ranf()functionRandomsamplinginnumpy|random_integers()functionNumpyufunc|UniversalfunctionsPythonPandasPandasTutorialIntroductiontoPandasinPythonHowtoInstallPythonPandasonWindowsandLinux?Python|PandasDataFrameCreatingaPandasDataFramePython|PandasSeriesCreatingaPandasSeriesPython|PandasDataframe/Series.head()methodPython|PandasDataframe.describe()methodDealingwithRowsandColumnsinPandasDataFramePython|PandasExtractingrowsusing.loc[]Python|ExtractingrowsusingPandas.iloc[]IndexingandSelectingDatawithPandasBooleanIndexinginPandasPandasGroupByPython|PandasMerging,Joining,andConcatenatingPython|WorkingwithdateandtimeusingPandasPython|PandasWorkingWithTextDataPython|Readcsvusingpandas.read_csv()Python|WorkingwithPandasandXlsxWriter|Set–1PythonDjangoDjangoTutorialDjangoBasicsDjangoIntroductionandInstallationDjangoProjectMVTStructureHowtoCreateaBasicProjectusingMVTinDjango?HowtoCreateanAppinDjango?DjangoFormsRenderHTMLForms(GET&POST)inDjangoDjangoformfieldcustomwidgetsDjangoModelForm–CreateformfromModelsDjangoFormsetsDjangoModelFormSetsDjangoTemplatesViewsInDjango|PythonDjangoCRUD(Create,Retrieve,Update,Delete)FunctionBasedViewsClassBasedGenericViewsDjango(Create,Retrieve,Update,Delete)DjangoModelsDjangoORM–Inserting,Updating&DeletingDataDjangoBasicAppModel–MakemigrationsandMigratePythonJSONPythonJSONWorkingWithJSONDatainPythonRead,WriteandParseJSONusingPythonAppendtoJSONfileusingPythonSerializingJSONdatainPythonDeserializeJSONtoObjectinPythonPythonCSVWorkingwithcsvfilesinPythonReadingCSVfilesinPythonWritingCSVfilesinPythonPythonMySQLPythonMySQLConnectMySQLdatabaseusingMySQL-ConnectorPythonPythonMySQL–CreateDatabasePython:MySQLCreateTablePythonMySQL–InsertintoTablePythonMySQL–SelectQueryPythonMySQL–WhereClausePythonMySQL–OrderByClausePythonMySQL–DeleteQueryPythonMySQL–DropTablePythonMySQL–UpdateQueryPythonMySQL–LimitClausePythonMySQL–JoinPythonMongoDBPythonMongoDBTutorialInstallingMongoDBonWindowswithPythonMongoDBandPythonCreateadatabaseinMongoDBusingPythonPythonMongoDB–insert_oneQueryPythonMongoDB–insert_manyQueryPythonMongoDB–FindPythonMongoDB–QueryPythonMongoDB–SortMongoDBpython|DeleteDataandDropCollectionPythonMongodb–Delete_one()PythonMongodb–Delete_many()PythonMongoDB–Update_one()PythonMongoDB–Update_manyQueryPythonMongoDB–LimitQueryPythonMongoDB–create_indexQueryPythonMongoDB–drop_indexQueryPythonOpenCVOpenCVPythonTutorialIntroductiontoOpenCVHowtoInstallOpenCVforPythononWindows?ReadinganimageinOpenCVusingPythonOpenCV|SavinganImageArithmeticOperationsonImagesusingOpenCV|Set-1(AdditionandSubtraction)ArithmeticOperationsonImagesusingOpenCV|Set-2(BitwiseOperationsonBinaryImages)ImageResizingusingOpenCV|PythonImageProcessinginPython(Scaling,Rotating,ShiftingandEdgeDetection)Python|ImageblurringusingOpenCVErosionandDilationofimagesusingOpenCVinpythonPython|ThresholdingtechniquesusingOpenCV|Set-1(SimpleThresholding)Python|ThresholdingtechniquesusingOpenCV|Set-2(AdaptiveThresholding)Python|ThresholdingtechniquesusingOpenCV|Set-3(OtsuThresholding)FilterColorwithOpenCVPython|BilateralFilteringPython|BackgroundsubtractionusingOpenCVPython|PlayavideousingOpenCVExtractimagesfromvideoinPythonFaceDetectionusingPythonandOpenCVwithwebcamPythonSeleniumSeleniumPythonTutorialSeleniumBasics–Components,Features,UsesandLimitationsComponentsofSeleniumSeleniumPythonIntroductionandInstallationNavigatinglinksusinggetmethod–SeleniumPythonInteractingwithWebpage–SeleniumPythonLocatingsingleelementsinSeleniumPythonLocatingmultipleelementsinSeleniumPythonLocatorStrategies–SeleniumPythonActionChainsinSeleniumPythonExceptions–SeleniumPythonPythonTkinterPythonTkinterTutorialIntroductiontoTkinterWhatareWidgetsinTkinter?Python|CreatingabuttonintkinterPythonTkinter–LabelRadioButtoninTkinter|PythonPythonTkinter–CheckbuttonWidgetPythonTkinter–CanvasWidgetComboboxWidgetintkinter|PythonPythonTkinter–EntryWidgetPythonTkinter–TextWidgetPythonTkinter–MessagePython|MenuwidgetinTkinterPythonTkinter–SpinBoxProgressbarwidgetinTkinter|PythonPython-TkinterScrollbarPythonTkinter–ScrolledTextWidgetPythonTkinter–ListBoxWidgetPythonTkinter–FrameWidgetPythonTkinter–ScaleWidgetHierarchicaltreeviewinPythonGUIapplicationPython-TkinterTreeviewscrollbarPythonTkinter–ToplevelWidgetPython|askopenfile()functioninTkinterPython|asksaveasfile()functioninTkinterPython–TkinteraskquestionDialogPythonTkinter–MessageBoxWidgetPython|place()methodinTkinterPython|grid()methodinTkinterPython|pack()methodinTkinterPython|PanedWindowWidgetinTkinterPython|BindingfunctioninTkinterPythonTkinter–ValidatingEntryWidgetPythonKivyKivyTutorialIntroductiontoKivy;ACross-platformPythonFrameworkPython|AddLabeltoakivywindowPython|TextinputwidgetinkivyPython|CanvasinkivyPython|CheckboxwidgetinKivyPython|DropdownlistinkivyPython|CarouselWidgetInKivyPython|BoxLayoutwidgetinKivyPython|SliderwidgetinKivyPython|PopupwidgetinKivyPython|SwitchwidgetinKivyPython|SpinnerwidgetinkivyPython|ProgressBarwidgetinkivyPython|WorkingwithbuttonsinKivyPython|FloatLayoutinKivyGridLayoutsinKivy|PythonPython|StackLayoutinKivyPython|AnchorLayoutinKivyPython|RelativeLayoutinKivyPython|PageLayoutinKivyDataVisualizationMatplotlibTutorialPythonSeabornTutorialPythonPlotlytutorialPythonBokehtutorial–InteractiveDataVisualizationwithBokehTableauTutorialPythonExamplesandQuizPythonProgrammingExamplesPythonExercises,PracticeQuestionsandSolutionsPythonMultipleChoiceQuestionsTableofContentsIntroductionPythonProgrammingLanguagePythonLanguageIntroductionPythonLanguageadvantagesandapplicationsDownloadandInstallPython3LatestVersionPython3basicsPythonKeywordsNamespacesandScopeinPythonStatement,IndentationandCommentinPythonHowtoassignvaluestovariablesinPythonandotherlanguagesInput/OutputTakinginputinPythonTakinginputfromconsoleinPythonTakingmultipleinputsfromuserinPythonPython|Outputusingprint()functionHowtoprintwithoutnewlineinPython?Pythonendparameterinprint()Python|sepparameterinprint()Python|OutputFormattingOperatorsPythonOperatorsTernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1OperatorFunctionsinPython|Set2Differencebetween==andisoperatorinPythonPythonMembershipandIdentityOperatorsDataTypesPython|Set3(Strings,Lists,Tuples,Iterations)PythonStringPythonListsPythonTuplesPythonSetsPythonDictionaryPythonArraysControlFlowPythonifelseChainingcomparisonoperatorsinPythonPythonForLoopsPythonWhileLoopPythonbreakstatementPythonContinueStatementPythonpassStatementLoopingTechniquesinPythonFunctionsPythonFunctions*argsand**kwargsinPythonWhentouseyieldinsteadofreturninPython?GeneratorsinPythonPythonlambdaGlobalandLocalVariablesinPythonGlobalkeywordinPythonFirstClassfunctionsinPythonPythonClosuresDecoratorsinPythonDecoratorswithparametersinPythonMemoizationusingdecoratorsinPythonPythonOOPPythonClassesandObjectsConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonClassorStaticVariablesinPythonClassmethodvsStaticmethodinPythonExceptionHandlingPythonExceptionHandlingPythonTryExceptErrorsandExceptionsinPythonBuilt-inExceptionsinPythonUser-definedExceptionsinPythonwithExamplesNZECerrorinPythonFilehandlingFileHandlinginPythonOpenaFileinPythonHowtoreadfromafileinPythonWritingtofileinPythonPythonappendtoafilePythonRegexRegularExpressioninPythonwithExamples|Set1RegularExpressionsinPython–Set2(Search,MatchandFindAll)PythonRegex:re.search()VSre.findall()VerboseinPythonRegexPasswordvalidationinPythonPythonCollectionsPythonCollectionsModuleCountersinPython|Set1(InitializationandUpdation)OrderedDictinPythonDefaultdictinPythonChainMapinPythonNamedtupleinPythonDequeinPythonHeapqueue(orheapq)inPythonCollections.UserDictinPythonCollections.UserListinPythonCollections.UserStringinPythonPythonAdvanceOSModuleinPythonwithExamplesFunctionalProgramminginPythonMetaprogrammingwithMetaclassesinPythonAbstractClassesinPythonMultithreadinginPython|Set1MultithreadinginPython|Set2(Synchronization)MultiprocessinginPython|Set1(Introduction)MultiprocessinginPython|Set2(Communicationbetweenprocesses)SocketProgramminginPythonSocketProgrammingwithMulti-threadinginPythonPythonNumPyNumPyTutorialPythonNumpyNumpy|ndarrayNumpy|ArrayCreationNumpy|IndexingBasicSlicingandAdvancedIndexinginNumPyPythonNumpy|DataTypeObjectsNumpy|IteratingOverArrayNumpy|BinaryOperationsNumpy|MathematicalFunctionNumpy|StringOperationsNumpy|LinearAlgebraNumpy|Sorting,SearchingandCountingRandomsamplinginnumpy|randint()functionRandomsamplinginnumpy|random_sample()functionRandomsamplinginnumpy|ranf()functionRandomsamplinginnumpy|random_integers()functionNumpyufunc|UniversalfunctionsPythonPandasPandasTutorialIntroductiontoPandasinPythonHowtoInstallPythonPandasonWindowsandLinux?Python|PandasDataFrameCreatingaPandasDataFramePython|PandasSeriesCreatingaPandasSeriesPython|PandasDataframe/Series.head()methodPython|PandasDataframe.describe()methodDealingwithRowsandColumnsinPandasDataFramePython|PandasExtractingrowsusing.loc[]Python|ExtractingrowsusingPandas.iloc[]IndexingandSelectingDatawithPandasBooleanIndexinginPandasPandasGroupByPython|PandasMerging,Joining,andConcatenatingPython|WorkingwithdateandtimeusingPandasPython|PandasWorkingWithTextDataPython|Readcsvusingpandas.read_csv()Python|WorkingwithPandasandXlsxWriter|Set–1PythonDjangoDjangoTutorialDjangoBasicsDjangoIntroductionandInstallationDjangoProjectMVTStructureHowtoCreateaBasicProjectusingMVTinDjango?HowtoCreateanAppinDjango?DjangoFormsRenderHTMLForms(GET&POST)inDjangoDjangoformfieldcustomwidgetsDjangoModelForm–CreateformfromModelsDjangoFormsetsDjangoModelFormSetsDjangoTemplatesViewsInDjango|PythonDjangoCRUD(Create,Retrieve,Update,Delete)FunctionBasedViewsClassBasedGenericViewsDjango(Create,Retrieve,Update,Delete)DjangoModelsDjangoORM–Inserting,Updating&DeletingDataDjangoBasicAppModel–MakemigrationsandMigratePythonJSONPythonJSONWorkingWithJSONDatainPythonRead,WriteandParseJSONusingPythonAppendtoJSONfileusingPythonSerializingJSONdatainPythonDeserializeJSONtoObjectinPythonPythonCSVWorkingwithcsvfilesinPythonReadingCSVfilesinPythonWritingCSVfilesinPythonPythonMySQLPythonMySQLConnectMySQLdatabaseusingMySQL-ConnectorPythonPythonMySQL–CreateDatabasePython:MySQLCreateTablePythonMySQL–InsertintoTablePythonMySQL–SelectQueryPythonMySQL–WhereClausePythonMySQL–OrderByClausePythonMySQL–DeleteQueryPythonMySQL–DropTablePythonMySQL–UpdateQueryPythonMySQL–LimitClausePythonMySQL–JoinPythonMongoDBPythonMongoDBTutorialInstallingMongoDBonWindowswithPythonMongoDBandPythonCreateadatabaseinMongoDBusingPythonPythonMongoDB–insert_oneQueryPythonMongoDB–insert_manyQueryPythonMongoDB–FindPythonMongoDB–QueryPythonMongoDB–SortMongoDBpython|DeleteDataandDropCollectionPythonMongodb–Delete_one()PythonMongodb–Delete_many()PythonMongoDB–Update_one()PythonMongoDB–Update_manyQueryPythonMongoDB–LimitQueryPythonMongoDB–create_indexQueryPythonMongoDB–drop_indexQueryPythonOpenCVOpenCVPythonTutorialIntroductiontoOpenCVHowtoInstallOpenCVforPythononWindows?ReadinganimageinOpenCVusingPythonOpenCV|SavinganImageArithmeticOperationsonImagesusingOpenCV|Set-1(AdditionandSubtraction)ArithmeticOperationsonImagesusingOpenCV|Set-2(BitwiseOperationsonBinaryImages)ImageResizingusingOpenCV|PythonImageProcessinginPython(Scaling,Rotating,ShiftingandEdgeDetection)Python|ImageblurringusingOpenCVErosionandDilationofimagesusingOpenCVinpythonPython|ThresholdingtechniquesusingOpenCV|Set-1(SimpleThresholding)Python|ThresholdingtechniquesusingOpenCV|Set-2(AdaptiveThresholding)Python|ThresholdingtechniquesusingOpenCV|Set-3(OtsuThresholding)FilterColorwithOpenCVPython|BilateralFilteringPython|BackgroundsubtractionusingOpenCVPython|PlayavideousingOpenCVExtractimagesfromvideoinPythonFaceDetectionusingPythonandOpenCVwithwebcamPythonSeleniumSeleniumPythonTutorialSeleniumBasics–Components,Features,UsesandLimitationsComponentsofSeleniumSeleniumPythonIntroductionandInstallationNavigatinglinksusinggetmethod–SeleniumPythonInteractingwithWebpage–SeleniumPythonLocatingsingleelementsinSeleniumPythonLocatingmultipleelementsinSeleniumPythonLocatorStrategies–SeleniumPythonActionChainsinSeleniumPythonExceptions–SeleniumPythonPythonTkinterPythonTkinterTutorialIntroductiontoTkinterWhatareWidgetsinTkinter?Python|CreatingabuttonintkinterPythonTkinter–LabelRadioButtoninTkinter|PythonPythonTkinter–CheckbuttonWidgetPythonTkinter–CanvasWidgetComboboxWidgetintkinter|PythonPythonTkinter–EntryWidgetPythonTkinter–TextWidgetPythonTkinter–MessagePython|MenuwidgetinTkinterPythonTkinter–SpinBoxProgressbarwidgetinTkinter|PythonPython-TkinterScrollbarPythonTkinter–ScrolledTextWidgetPythonTkinter–ListBoxWidgetPythonTkinter–FrameWidgetPythonTkinter–ScaleWidgetHierarchicaltreeviewinPythonGUIapplicationPython-TkinterTreeviewscrollbarPythonTkinter–ToplevelWidgetPython|askopenfile()functioninTkinterPython|asksaveasfile()functioninTkinterPython–TkinteraskquestionDialogPythonTkinter–MessageBoxWidgetPython|place()methodinTkinterPython|grid()methodinTkinterPython|pack()methodinTkinterPython|PanedWindowWidgetinTkinterPython|BindingfunctioninTkinterPythonTkinter–ValidatingEntryWidgetPythonKivyKivyTutorialIntroductiontoKivy;ACross-platformPythonFrameworkPython|AddLabeltoakivywindowPython|TextinputwidgetinkivyPython|CanvasinkivyPython|CheckboxwidgetinKivyPython|DropdownlistinkivyPython|CarouselWidgetInKivyPython|BoxLayoutwidgetinKivyPython|SliderwidgetinKivyPython|PopupwidgetinKivyPython|SwitchwidgetinKivyPython|SpinnerwidgetinkivyPython|ProgressBarwidgetinkivyPython|WorkingwithbuttonsinKivyPython|FloatLayoutinKivyGridLayoutsinKivy|PythonPython|StackLayoutinKivyPython|AnchorLayoutinKivyPython|RelativeLayoutinKivyPython|PageLayoutinKivyDataVisualizationMatplotlibTutorialPythonSeabornTutorialPythonPlotlytutorialPythonBokehtutorial–InteractiveDataVisualizationwithBokehTableauTutorialPythonExamplesandQuizPythonProgrammingExamplesPythonExercises,PracticeQuestionsandSolutionsPythonMultipleChoiceQuestionsImproveArticle
SaveArticle
LikeArticle
OSModuleinPythonwithExamplesDifficultyLevel:
EasyLastUpdated:
25Jan,2022TheOSmoduleinPythonprovidesfunctionsforinteractingwiththeoperatingsystem.OScomesunderPython’sstandardutilitymodules.Thismoduleprovidesaportablewayofusingoperatingsystem-dependentfunctionality.The*os*and*os.path*modulesincludemanyfunctionstointeractwiththefilesystem. HandlingtheCurrentWorkingDirectoryConsiderCurrentWorkingDirectory(CWD)asafolder,wherethePythonisoperating.Wheneverthefilesarecalledonlybytheirname,PythonassumesthatitstartsintheCWDwhichmeansthatname-onlyreferencewillbesuccessfulonlyifthefileisinthePython’sCWD.Note:ThefolderwherethePythonscriptisrunningisknownastheCurrentDirectory.ThisisnotthepathwherethePythonscriptislocated.GettingtheCurrentworkingdirectoryTogetthelocationofthecurrentworkingdirectoryos.getcwd()isused. Example:Python3#Pythonprogramtoexplainos.getcwd()method #importingosmoduleimportos #Getthecurrentworking#directory(CWD)cwd=os.getcwd() #Printthecurrentworking#directory(CWD)print("Currentworkingdirectory:",cwd)Output:Currentworkingdirectory:/home/nikhil/Desktop/gfgChangingtheCurrentworkingdirectoryTochangethecurrentworkingdirectory(CWD)os.chdir()methodisused.ThismethodchangestheCWDtoaspecifiedpath.Itonlytakesasingleargumentasanewdirectorypath. Note:ThecurrentworkingdirectoryisthefolderinwhichthePythonscriptisoperating. Example:Python3#Pythonprogramtochangethe#currentworkingdirectory importos #FunctiontoGetthecurrent #workingdirectorydefcurrent_path(): print("Currentworkingdirectorybefore") print(os.getcwd()) print() #Driver'scode#PrintingCWDbeforecurrent_path() #ChangingtheCWDos.chdir('../') #PrintingCWDaftercurrent_path()Output:Currentworkingdirectorybefore
C:\Users\NikhilAggarwal\Desktop\gfg
Currentworkingdirectoryafter
C:\Users\NikhilAggarwal\Desktop CreatingaDirectoryTherearedifferentmethodsavailableintheOSmoduleforcreatingadirectory.Theseare–os.mkdir()os.makedirs()Usingos.mkdir()os.mkdir()methodinPythonisusedtocreateadirectorynamedpathwiththespecifiednumericmode.ThismethodraisesFileExistsErrorifthedirectorytobecreatedalreadyexists. Example: Python3#Pythonprogramtoexplainos.mkdir()method #importingosmoduleimportos #Directorydirectory="GeeksforGeeks" #ParentDirectorypathparent_dir="D:/Pycharmprojects/" #Pathpath=os.path.join(parent_dir,directory) #Createthedirectory#'GeeksForGeeks'in#'/home/User/Documents'os.mkdir(path)print("Directory'%s'created"%directory) #Directorydirectory="Geeks" #ParentDirectorypathparent_dir="D:/Pycharmprojects" #modemode=0o666 #Pathpath=os.path.join(parent_dir,directory) #Createthedirectory#'GeeksForGeeks'in#'/home/User/Documents'#withmode0o666os.mkdir(path,mode)print("Directory'%s'created"%directory)Output:Directory'GeeksforGeeks'created
Directory'Geeks'createdUsingos.makedirs()os.makedirs()methodinPythonisusedtocreateadirectoryrecursively.Thatmeanswhilemakingleafdirectoryifanyintermediate-leveldirectoryismissing,os.makedirs()methodwillcreatethemall. Example: Python3#Pythonprogramtoexplainos.makedirs()method #importingosmoduleimportos #Leafdirectorydirectory="Nikhil" #ParentDirectoriesparent_dir="D:/Pycharmprojects/GeeksForGeeks/Authors" #Pathpath=os.path.join(parent_dir,directory) #Createthedirectory#'Nikhil'os.makedirs(path)print("Directory'%s'created"%directory) #Directory'GeeksForGeeks'and'Authors'will#becreatedtoo#ifitdoesnotexists #Leafdirectorydirectory="c" #ParentDirectoriesparent_dir="D:/Pycharmprojects/GeeksforGeeks/a/b" #modemode=0o666 path=os.path.join(parent_dir,directory) #Createthedirectory'c' os.makedirs(path,mode)print("Directory'%s'created"%directory) #'GeeksForGeeks','a',and'b'#willalsobecreatedif#itdoesnotexists #Ifanyoftheintermediatelevel#directoryismissing#os.makedirs()methodwill#createthem #os.makedirs()methodcanbe#usedtocreateadirectorytreeOutput:Directory'Nikhil'created
Directory'c'createdListingoutFilesandDirectorieswithPythonos.listdir()methodinPythonisusedtogetthelistofallfilesanddirectoriesinthespecifieddirectory.Ifwedon’tspecifyanydirectory,thenthelistoffilesanddirectoriesinthecurrentworkingdirectorywillbereturned. Example:Python3#Pythonprogramtoexplainos.listdir()method #importingosmoduleimportos #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'] DeletingDirectoryorFilesusingPythonOSmoduleprovesdifferentmethodsforremovingdirectoriesandfilesinPython.Theseare– Usingos.remove()Usingos.rmdir()Usingos.remove()os.remove()methodinPythonisusedtoremoveordeleteafilepath.Thismethodcannotremoveordeleteadirectory.IfthespecifiedpathisadirectorythenOSErrorwillberaisedbythemethod. Example:Supposethefilecontainedinthefolderare: Python3#Pythonprogramtoexplainos.remove()method #importingosmoduleimportos #Filenamefile='file1.txt' #Filelocationlocation="D:/Pycharmprojects/GeeksforGeeks/Authors/Nikhil/" #Pathpath=os.path.join(location,file) #Removethefile#'file.txt'os.remove(path)e)Output:Usingos.rmdir()os.rmdir()methodinPythonisusedtoremoveordeleteanemptydirectory.OSErrorwillberaisedifthespecifiedpathisnotanemptydirectory. Example:Supposethedirectoriesare Python3#Pythonprogramtoexplainos.rmdir()method #importingosmoduleimportos #Directorynamedirectory="Geeks" #ParentDirectoryparent="D:/Pycharmprojects/" #Pathpath=os.path.join(parent,directory) #RemovetheDirectory#"Geeks"os.rmdir(path)Output: CommonlyUsedFunctions1.os.name:Thisfunctiongivesthenameoftheoperatingsystemdependentmoduleimported.Thefollowingnameshavecurrentlybeenregistered:‘posix’,‘nt’,‘os2’,‘ce’,‘java’and‘riscos’.Python3importos print(os.name)Output:posixNote:Itmaygivedifferentoutputondifferentinterpreters,suchas‘posix’whenyourunthecodehere. 2.os.error:AllfunctionsinthismoduleraiseOSErrorinthecaseofinvalidorinaccessiblefilenamesandpaths,orotherargumentsthathavethecorrecttype,butarenotacceptedbytheoperatingsystem.os.errorisanaliasforbuilt-inOSErrorexception. Python3importos try: #Ifthefiledoesnotexist, #thenitwouldthrowanIOError filename='GFG.txt' f=open(filename,'rU') text=f.read() f.close() #Controljumpsdirectlytohereif#anyoftheabovelinesthrowsIOError. exceptIOError: #print(os.error)will
延伸文章資訊
- 1Python 速查手冊- 12.5 基本檔案與目錄處理os 與os.path
本篇文章介紹Python 標準程式庫的os 與os.path 模組。 ... os 與os.path 為處理作業系統相關及目錄路徑的模組(module) , os 有以下的常用常數 ...
- 230 Useful Methods from python OS Module - Analytics Vidhya
The python os module makes this possible, it provides a means for us to interact with the underly...
- 3os — Miscellaneous operating system interfaces — Python ...
The design of all built-in operating system dependent modules of Python is such that as long as t...
- 4【python基礎】os模組的使用 - IT人
os簡介os 模組是關於作業系統操作呼叫的相關模組,對檔案進行重新命名、刪除等一系列操作,在python中可以用os模組os模組提供了一些系統級別的操作 ...
- 5Python中import os是什么意思? - 知乎
首先合法的package必须含有一个__init__.py文件,package可以包含0个或多个module(py文件)。假设aa文件夹中有test.py文件和bb文件夹,bb文件夹里面有c.p...