Random bytes with os.urandom()

Random bytes with os.urandom()

EasyOS Module Programs · 27 of 49

Write a Python program to get random bytes with os.urandom() and turn them into a string.

Output
bytes 8
16

Approach

  1. os.urandom(n) returns n cryptographically strong random bytes.

Solution

Python
import os data = os.urandom(8)print(type(data).__name__, len(data))print(len(data.hex()))
Output
bytes 8
16

Line by line

Line 3

The bytes differ on every run; hex() turns 8 bytes into 16 hexadecimal characters.

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Read command-line arguments

Read command-line arguments

EasyOS Module Programs · 24 of 49

Write a Python program that reads arguments passed on the command line.

Output
arguments: ['chrome', '--headless']

Approach

  1. Start a child Python with arguments and read them from sys.argv.

Solution

Python
import subprocessimport sys with open("args_demo.py", "w") as f:    f.write("import sys\nprint('arguments:', sys.argv[1:])\n")out = subprocess.run([sys.executable, "args_demo.py", "chrome", "--headless"], capture_output=True, text=True)print(out.stdout.strip())
Output
arguments: ['chrome', '--headless']

Line by line

Lines 4-5

Writes a tiny script that prints its arguments.

Line 6

Runs it the way you would type python args_demo.py chrome --headless.

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Backup sorted by extension

Backup sorted by extension

MediumOS Module Programs · 22 of 49

Write a Python backup program that copies every file into a folder named after its extension.

Output
csv ['d.csv']
py ['a.py', 'b.py']
txt ['c.txt']

Approach

  1. Walk the source, compute the extension and copy into backup/<ext>/.

Solution

Python
import osimport shutil os.makedirs("project/docs", exist_ok=True)for path in ["project/a.py", "project/b.py", "project/docs/c.txt", "project/d.csv"]:    with open(path, "w") as f:        f.write("x") for folder, _, files in os.walk("project"):    for name in files:        ext = os.path.splitext(name)[1].lstrip(".") or "no_ext"        target = os.path.join("backup", ext)        os.makedirs(target, exist_ok=True)        shutil.copy2(os.path.join(folder, name), target) for ext in sorted(os.listdir("backup")):    print(ext, sorted(os.listdir(os.path.join("backup", ext))))
Output
csv ['d.csv']
py ['a.py', 'b.py']
txt ['c.txt']

Line by line

Lines 9-14

Every file found by os.walk is copied into a folder for its extension; files without one go to “no_ext”.

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Run a system command

Run a system command

EasyOS Module Programs · 23 of 49

Write a Python program to run an operating system command and read its output.

Output
return code: 0
Python 3.15.1
hello from the shell

Approach

  1. subprocess.run with capture_output=True is the modern way.

Solution

Python
import subprocessimport sys result = subprocess.run([sys.executable, "--version"], capture_output=True, text=True)print("return code:", result.returncode)print(result.stdout.strip()) echo = subprocess.run("echo hello from the shell", shell=True, capture_output=True, text=True)print(echo.stdout.strip())
Output
return code: 0
Python 3.15.1
hello from the shell

Line by line

Line 4

Passing a list runs the program directly, without a shell, which is safer.

Line 8

shell=True lets you use shell commands such as echo or dir; never combine it with untrusted input.

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Remove files of one extension

Remove files of one extension

EasyOS Module Programs · 21 of 49

Write a Python program to remove all files with a specific extension from a folder.

Output
['keep.txt']

Approach

  1. Loop over the folder and remove matching files.

Solution

Python
import os os.makedirs("logs", exist_ok=True)for name in ["a.log", "b.log", "keep.txt"]:    open(os.path.join("logs", name), "w").close()for name in os.listdir("logs"):    if name.endswith(".log"):        os.remove(os.path.join("logs", name))print(os.listdir("logs"))
Output
['keep.txt']

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Remove a file

Remove a file

EasyOS Module Programs · 20 of 49

Write a Python program to remove a file at a given path.

Output
False

Approach

  1. os.remove(); check that it exists first.

Solution

Python
import os open("old.log", "w").close()if os.path.exists("old.log"):    os.remove("old.log")print(os.path.exists("old.log"))
Output
False

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Copy files of one extension

Copy files of one extension

EasyOS Module Programs · 18 of 49

Write a Python program to copy only the files with a specific extension.

Output
['a.csv', 'c.csv']

Approach

  1. Filter names with endswith, then copy.

Solution

Python
import osimport shutil os.makedirs("src", exist_ok=True)os.makedirs("only_csv", exist_ok=True)for name in ["a.csv", "b.txt", "c.csv"]:    open(os.path.join("src", name), "w").close()for name in os.listdir("src"):    if name.endswith(".csv"):        shutil.copy(os.path.join("src", name), "only_csv")print(sorted(os.listdir("only_csv")))
Output
['a.csv', 'c.csv']

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Copy a file into 10 nested folders

Copy a file into 10 nested folders

MediumOS Module Programs · 19 of 49

Write a Python program to copy a file into 10 different nested directories.

Output
10 ['file1.txt', 'file2.txt']

Approach

  1. Build deeper paths in a loop and copy the file into each.

Solution

Python
import osimport shutil with open("seed.txt", "w") as f:    f.write("sample")path = "tree"for i in range(1, 11):    path = os.path.join(path, f"d{i}")    os.makedirs(path, exist_ok=True)    shutil.copy("seed.txt", os.path.join(path, f"file{i}.txt")) copies = [f for _, _, files in os.walk("tree") for f in files]print(len(copies), copies[:2])
Output
10 ['file1.txt', 'file2.txt']

Line by line

Lines 6-9

Each pass goes one folder deeper and copies the file there.

Line 11

os.walk visits every folder, so all 10 copies are found.

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Copy a file

Copy a file

EasyOS Module Programs · 17 of 49

Write a Python program to copy a file from a source path to a target path.

Output
quarterly report

Approach

  1. shutil.copy copies data and permissions; copy2 also copies timestamps.

Solution

Python
import osimport shutil os.makedirs("src", exist_ok=True)os.makedirs("dst", exist_ok=True)with open("src/report.txt", "w") as f:    f.write("quarterly report")shutil.copy2("src/report.txt", "dst/report.txt")print(open("dst/report.txt").read())
Output
quarterly report

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Count files per extension

Count files per extension

EasyOS Module Programs · 16 of 49

Write a Python program to count the files of each extension in a target path.

Output
{'.csv': 1, '.py': 3, '.txt': 2}

Approach

  1. os.path.splitext plus Counter.

Solution

Python
import osfrom collections import Counter os.makedirs("target", exist_ok=True)for name in ["a.txt", "b.txt", "c.csv", "d.py", "e.py", "f.py"]:    open(os.path.join("target", name), "w").close()counts = Counter(os.path.splitext(n)[1] for n in os.listdir("target"))print(dict(sorted(counts.items())))
Output
{'.csv': 1, '.py': 3, '.txt': 2}

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs