Python Tutorial: os module for beginners

Pubblicato il: 26 luglio 2024
sul canale di: 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


In questa pagina del sito puoi guardare il video online Python Tutorial: os module for beginners della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Ferds Tech Channel 26 luglio 2024, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 74 volte e gli è piaciuto 2 spettatori. Buona visione!