OS Module in Python with Examples - GeeksforGeeks

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

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    print('Problemreading:'+filename)     #Inanycase,thecodethencontinueswith#thelineafterthetry/exceptOutput: Problemreading:GFG.txt 3.os.popen():Thismethodopensapipetoorfromcommand.Thereturnvaluecanbereadorwrittendependingonwhetherthemodeis‘r’or‘w’. Syntax: os.popen(command[,mode[,bufsize]])Parametersmode&bufsizearenotnecessaryparameters,ifnotprovided,default‘r’istakenformode. Python3importosfd="GFG.txt" #popen()issimilartoopen()file=open(fd,'w')file.write("Hello")file.close()file=open(fd,'r')text=file.read()print(text) #popen()providesapipe/gatewayandaccessesthefiledirectlyfile=os.popen(fd,'w')file.write("Hello")#Filenotclosed,showninnextfunction.Output: HelloNote:Outputforpopen()willnotbeshown,therewouldbedirectchangesintothefile. 4.os.close():Closefiledescriptorfd.Afileopenedusingopen(),canbeclosedbyclose()only.Butfileopenedthroughos.popen(),canbeclosedwithclose()oros.close().Ifwetryclosingafileopenedwithopen(),usingos.close(),PythonwouldthrowTypeError. Python3importos  fd="GFG.txt"file=open(fd,'r')text=file.read()print(text)os.close(file)Output: Traceback(mostrecentcalllast): File"C:\Users\GFG\Desktop\GeeksForGeeksOSFile.py",line6,in os.close(file) TypeError:anintegerisrequired(gottype_io.TextIOWrapper)Note:Thesameerrormaynotbethrown,duetothenon-existentfileorpermissionprivilege. 5.os.rename():Afileold.txtcanberenamedtonew.txt,usingthefunctionos.rename().Thenameofthefilechangesonlyif,thefileexistsandtheuserhassufficientprivilegepermissiontochangethefile.Pythonimportos  fd="GFG.txt"os.rename(fd,'New.txt')os.rename(fd,'New.txt')Output:Traceback(mostrecentcalllast): File"C:\Users\GFG\Desktop\ModuleOS\GeeksForGeeksOSFile.py",line3,in os.rename(fd,'New.txt') FileNotFoundError:[WinError2]Thesystemcannotfindthe filespecified:'GFG.txt'->'New.txt'UnderstandingtheOutput:Afilename“GFG.txt”exists,thuswhenos.rename()isusedthefirsttime,thefilegetsrenamed.Uponcallingthefunctionos.rename()secondtime,file“New.txt”existsandnot“GFG.txt” thusPythonthrowsFileNotFoundError.  6.os.remove():UsingtheOsmodulewecanremoveafileinoursystemusingtheremove()method.Toremoveafileweneedtopassthenameofthefileasaparameter. Python3importos#importingosmodule. os.remove("file_name.txt")#removingthefile.TheOSmoduleprovidesusalayerofabstractionbetweenusandtheoperatingsystem.Whenweareworkingwithosmodulealwaysspecifytheabsolutepathdependingupontheoperatingsystemthecodecanrunonanyosbutweneedtochangethepathexactly.IfyoutrytoremoveafilethatdoesnotexistyouwillgetFileNotFoudError. 7.os.path.exists():Thismethodwillcheckwhetherafileexistsornotbypassingthenameofthefileasaparameter.OSmodulehasasub-modulenamedPATHbyusingwhichwecanperformmanymorefunctions. Python3importos#importingosmodule result=os.path.exists("file_name")#givingthenameofthefileasaparameter. print(result)OutputFalseAsintheabovecode,thefiledoesnotexistitwillgiveoutputFalse.IfthefileexistsitwillgiveusoutputTrue. 8.os.path.getsize():Inthismethod,pythonwillgiveusthesizeofthefileinbytes.Tousethismethodweneedtopassthenameofthefileasaparameter.Python3importos#importingosmodule size=os.path.getsize("filename") print("Sizeofthefileis",size,"bytes.")Output:Sizeofthefileis192bytes.ThisarticleiscontributedbyPiyushDoorwar.IfyoulikeGeeksforGeeksandwouldliketocontribute,youcanalsowriteanarticleusingwrite.geeksforgeeks.orgormailyourarticletoreview-team@geeksforgeeks.org.SeeyourarticleappearingontheGeeksforGeeksmainpageandhelpotherGeeks.Pleasewritecommentsifyoufindanythingincorrect,oryouwanttosharemoreinformationaboutthetopicdiscussedabove.MyPersonalNotes arrow_drop_upSave LikePreviousCollections.UserStringinPythonNext FunctionalProgramminginPythonRecommendedArticlesPage:21,May1904,Mar2028,May2010,Nov1612,Jan1719,May1731,May1703,Oct1803,May1828,Oct1705,Nov1705,Nov1724,Apr1809,Jan1819,Jan1814,Mar2106,Apr1816,Apr1824,Apr1824,Apr1824,Apr1830,Apr1801,May1815,Jun18ArticleContributedBy:GeeksforGeeksVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:Akanksha_Raimejustmyself9ddeevviissaavviittaaharshkesamartyaghoshgfgArticleTags:python-modulespython-os-modulePythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinPythonReadJSONfileusingPythonAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionHowtogetcolumnnamesinPandasdataframeReadafilelinebylineinPythonMorerelatedarticlesinPythonEnumerate()inPythonHowtoInstallPIPonWindows?IterateoveralistinPythonDifferentwaystocreatePandasDataframePythonString|replace()× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?