Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Python - OS Module

It is possible to automatically perform many operating system tasks. The OS module in Python provides functions for creating and removing a directory (folder), fetching its contents, changing and identifying the current directory, etc.

You first need to import the os module to interact with the underlying operating system. So, import it using the import os statement before using its functions.

Getting Current Working Directory

The getcwd() function confirms returns the current working directory.

Example: Get Current Working Directory
import os

print(os.getcwd())  #output: 'C:\Python37'

Creating a Directory

We can create a new directory using the os.mkdir() function, as shown below.

Example: Create a Physical Directory
import os

os.mkdir("C:MyPythonProject")

A new directory corresponding to the path in the string argument of the function will be created. If you open the C:\ drive, then you will see the MyPythonProject folder has been created.

By default, if you don't specify the whole path in the mkdir() function, it will create the specified directory in the current working directory or drive. The following will create MyPythonProject in the C:\Python37 directory.

Example: Create a Physical Directory
import os

print(os.getcwd())  #output: 'C:Python37'
os.mkdir("MyPythonProject")

Changing the Current Working Directory

We must first change the current working directory to a newly created one before doing any operations in it. This is done using the chdir() function. The following change current working directory to C:\MyPythonProject.

Example: Change Working Directory
import os

os.chdir("C:MyPythonProject") # changing current workign directory
print(os.getcwd())  #output: 'C:MyPythonProject'

You can change the current working directory to a drive. The following makes the C:\ drive as the current working directory.

Example: Change Directory to Drive
os.chdir("C:\")
print(os.getcwd())  #output: 'C:\'

In order to set the current directory to the parent directory use ".." as the argument in the chdir() function.

Example: Change CWD to Parent
os.chdir("C:\MyPythonProject")

print(os.getcwd())  #output: 'C:\MyPythonProject'
os.chdir("..")
print(os.getcwd()) #output: 'C:\'

Removing a Directory

The rmdir() function in the OS module removes the specified directory either with an absolute or relative path. Note that, for a directory to be removed, it should be empty.

Example: Remove Directory
import os

os.rmdir("C:\MyPythonProject")

However, you can not remove the current working directory. To remove it, you must change the current working directory, as shown below.

Example: Remove Directory
import os

print(os.getcwd())  #output: 'C:\MyPythonProject'

os.rmdir("C:\MyPythonProject") #PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
os.chdir("..")
os.rmdir("MyPythonProject")

Above, the MyPythonProject will not be removed because it is the current directory. We changed the current working directory to the parent directory using os.chdir("..") and then remove it using the rmdir() function.

List Files and Sub-directories

The listdir() function returns the list of all files and directories in the specified directory.

Example: List Directories
import os

print(os.listdir("c:python37"))

If we don't specify any directory, then list of files and directories in the current working directory will be returned.

Example: List Directories of CWD
import os

print(os.listdir())  #output: ['.config', '.dotnet', 'python']

Learn more about OS modules in Python docs.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.