Python Tutorial: os module for beginners

Опубликовано: 01 Октябрь 2024
на канале: Ferds Tech Channel
74
2

In this video, I will cover the os module in python.

The os module in Python provides a way to interact with the operating system.
It allows you to handle environment variables, perform file operations, and more.

import os

Get the current working directory:
current_directory = os.getcwd()
print("Current working directory:", current_directory)

List the contents of a directory:
print('Directory contents:', os.listdir('.'))

Create a new directory:
os.mkdir('new_directory')
print('Created directory: new_directory')

Delete a file:
os.remove('file_to_delete.txt')
print('Deleted file: file_to_delete.txt')

Join paths:
file_path = os.path.join('folder', 'file.txt')
print('Joined path:', file_path)

Check if a path exists, or if it’s a file or directory:
print('Path exists:', os.path.exists('file.txt'))
print('Is file:', os.path.isfile('file.txt'))
print('Is directory:', os.path.isdir('directory'))

Execute a shell command:
os.system('dir')

Identify the OS type:
print('OS name:', os.name)

View all environment variables:
for key, value in os.environ.items():
print(f'{key}: {value}')

Set an environment variable:
os.environ['TEST_VARIABLE'] = 'test_value'
print('MY_TEST_VARIABLE:', os.getenv('TEST_VARIABLE'))

Get the value of an environment variable:
test_var = os.getenv('TEST_VARIABLE')
print('MY_VARIABLE:', test_var)

Delete an environment variable:
if 'TEST_VARIABLE' in os.environ:
del os.environ['TEST_VARIABLE']
print('TEST_VARIABLE deleted.')
else:
print('TEST_VARIABLE does not exist.')

#python #pythonforbeginners #programming