?print-pdf' Created for
C:\Users\nemsys\tmp.txt
/home/nemsys/tmp.txt
# Windows (the CWD is shown in the prompt )
C:\Users\nemsys\MyDocuments>cd
C:\Users\nemsys\MyDocuments
# Linux/MacOS
nemsys@debian:~/Documents$ pwd
/home/nemsys/Documents
absolute_path = r"C:\Users\Username\Documents\example.txt"
absolute_path = "/home/username/Documents/example.txt"
# if CWD = '/home/username'
relative_path = "Documents/example.txt"
os.getcwd() and os.chdir()
import os
cwd = os.getcwd()
print("Current Working Directory:", cwd)
import os
# Change the directory to "/path/to/your/directory"
os.chdir("/path/to/your/directory")
# Verify the change
new_dir = os.getcwd()
print("The current working directory has been changed to:", new_dir)
os.listdir()
import os
contents = os.listdir("directory_path")
print(contents)
# Output: ['file1.txt', 'file2.txt', 'folder1', 'folder2']
import os
# get list of files only:
files = [f for f in os.listdir("directory_path") if os.path.isfile(f)]
print(files)
# Output: ['file1.txt', 'file2.txt']
os.walk()
def list_dir_contents(dir_path):
"""
This function recursively iterates through the directory tree, yielding root, dirs, and files at each level.
It then prints the full path of each directory and file
Args:
dir_path: The path to the directory to list.
Returns:
None
"""
for root, dirs, files in os.walk(dir_path):
for directory in dirs:
full_dir_path = os.path.join(root, directory)
print(f"Directory: {full_dir_path}\n")
for filename in files:
full_file_path = os.path.join(root, filename)
print(f"File: {full_file_path}\n")
dir_path = os.getcwd()
list_dir_contents(dir_path)
os.mkdir() and os.makedirs()
import os
os.mkdir("parent_directory")
import os
os.makedirs("parent_directory/child_directory")
os.rmdir() and shutil.rmtree()
import os
os.rmdir("directory_path")
os.rmdir() removes only empty directory. Otherwise, OSError is raised.os.removedirs(), which will delete even non-empty directories.
import shutil
shutil.rmtree("directory_path")
import os
joined_path = os.path.join("folder", "file.txt")
print("Joined Path:", joined_path)
# Output: Joined Path: folder/file.txt
import os
abs_path = os.path.abspath("file.txt")
print("Absolute Path:", abs_path)
# Output: Absolute Path: /full/path/to/file.txt
import os
file_name = os.path.basename("/path/to/file.txt")
print("File Name:", file_name)
# Output: File Name: file.txt
import os
dir_name = os.path.dirname("/path/to/file.txt")
print("Directory Name:", dir_name)
# Output: Directory Name: /path/to
import os
path = "/path/to/file.txt"
exists = os.path.exists(path)
print("Path Exists:", exists)
# Output: Path Exists: True (or False if the path doesn't exist)
import os
file_path = "/path/to/file.txt"
is_file = os.path.isfile(file_path)
print("Is a File:", is_file)
# Output: Is a File: True (or False if the path is not a file)
import os
dir_path = "/path/to/directory"
is_dir = os.path.isdir(dir_path)
print("Is a Directory:", is_dir)
# Output: Is a Directory: True (or False if the path is not a directory)
import os
print(os.name)
import os
print(os.environ)
import os
os.system('echo Hello World')
sys modulesys modulesys is a built-in module, which contains Python interpreter's specific parameters and functions
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '
_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'ba
se_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix
', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getdlopen
flags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementa
tion', 'int_info', 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path
_importer_cache', 'platform', 'prefix', 'set_coroutine_wrapper', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrac
e', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions']
sys.version - A string containing the version number of the Python interpreter plus additional information.sys.version_info - A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial.
import sys
print(sys.version)
# 3.12.0 (main, Jan 2 2024, 16:26:01) [GCC 11.4.0]
print(sys.version_info)
# sys.version_info(major=3, minor=12, micro=0, releaselevel='final', serial=0)
import sys
if sys.version_info[0] == 2:
print("This program requires Python 3 or above. You are using Python 2.")
elif sys.version_info[0] == 3:
print("Python 3 is running")
sys.executable - A string giving the absolute path of the executable binary for the Python interpreter
import sys
print(sys.executable)
#/usr/bin/python3
sys.path - A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.
import sys
for path in sys.path:
print(path)
#/media/user/data/projects/examples
#/usr/lib/python312.zip
#/usr/lib/python3.12
#/usr/lib/python3.12/lib-dynload
#/usr/local/lib/python3.12/dist-packages
#/usr/lib/python3/dist-packages
#/usr/lib/python3.12/dist-packages
sys.path list:
import sys
# add 'my_modules' to path:
sys.path.append('/media/user/data/my_modules')
from module1 import foo
foo()
sys.getsizeof() - Return the size of an object in bytes.sys.getsizeof() function returns the size of the object itself, not the size of the elements it contains or references.
import sys
from functools import reduce
x = 1000
l = [1,2,3,4,5,6,7,8,9,10]
int_object_memory = sys.getsizeof(x)
list_object_memory = sys.getsizeof(l)
list_elements_memory = reduce( lambda a,el: a+sys.getsizeof(el), l, 0)
print(int_object_memory) # 28
print(list_object_memory) # 136
print(list_elements_memory) # 280
sys.exit([status]) - Terminate the script with an optional exit status.
import sys
sys.exit(0) # successful termination
sys.argv: accessing command-line argumentssys.argv: accessing command-line arguments
$ python greet_user.py --help
Usage: python greet_user.py [options]
Options:
--help Show this help message
--name User name (string)
--age User age (integer)
$ python greet_user.py --name=Ada --age=23
sys.argv list:sys.argv[0] will always store the script name.sys.argv[1:]
import sys
print(f"Script Name: {sys.argv[0]}")
print(f"Arguments: {sys.argv[1:]}")
###Output of: python greet_user.py --name=Ada --age=23
#Script Name: greet_user.py
#Arguments: ['--name=Ada', '--age=23']
import sys
print('Argument List:', sys.argv)
# call script without arguments:
$ python argv_examples.py
Argument List: ['argv_examples.py']
# call script with 1 argument:
$ python argv_examples.py arg1
Argument List: ['argv_examples.py', 'arg1']
# call script with 3 arguments:
$ python argv_examples.py arg1 23 -45.6
Argument List: ['argv_examples.py', 'arg1', '23', '-45.6']
import argparse
# Create the parser
parser = argparse.ArgumentParser(description='Example script demonstrating argparse usage.')
# define positional required argument:
parser.add_argument('message', help='the message to be repeated')
# define optional argument:
parser.add_argument('--repeat', type=int, default=1, help='How many times to repeat the message (default: %(default)s)')
# Parse arguments
args = parser.parse_args()
# Use arguments
for _ in range(args.repeat):
print(args.message)
###Output of: $ python echo.py hello --repeat 3
# hello
# hello
# hello
###Output of: $ python echo.py --help
# usage: echo.py [-h] [--repeat REPEAT] message
# Example script demonstrating argparse usage.
# positional arguments:
# message the message to be repeated
# options:
# -h, --help show this help message and exit
# --repeat REPEAT How many times to repeat the message (default: 1)
###Output of: python3 echo.py
# usage: echo.py [-h] [--repeat REPEAT] message
# echo.py: error: the following arguments are required: message
message) that are required, and optional arguments (here, --repeat) that the user can specify to alter the script's behavior.