Python File System Operations and Utilities

Delete files with .tmp extension in a directory:

import os, glob

target_dir = '/var/tmp'
files = glob.glob(os.path.join(target_dir, '*'))
for file_path in files:
    if file_path.endswith('.tmp'):
        try:
            os.remove(file_path)
        except OSError:
            pass

Finding Largest Files

Identify two largest files in a directory tree:

import os

root_dir = '/var/log'
file_sizes = []
for root, dirs, files in os.walk(root_dir):
    for file_name in files:
        full_path = os.path.join(root, file_name)
        size = os.path.getsize(full_path)
        file_sizes.append((size, full_path))
        
file_sizes.sort()
print(file_sizes[-2:])

Recursive Directory Removal

Delete all contents in a directory tree:

import os

top_dir = '/tmp/to_remove'
for root, dirs, files in os.walk(top_dir, topdown=False):
    for file_name in files:
        os.remove(os.path.join(root, file_name))
    for dir_name in dirs:
        os.rmdir(os.path.join(root, dir_name))

File Sequence Deletion

Remove numbered file sequences:

import os

sequence_path = input('Sequence path: ')
start_frame = int(input('Start frame: '))
end_frame = int(input('End frame: '))

base_path, file_pattern = os.path.split(sequence_path.strip())
name_parts = file_pattern.split('#')
padding_length = len(name_parts[1:-1]) + 1

for frame_num in range(start_frame, end_frame + 1):
    frame_str = str(frame_num).zfill(padding_length)
    file_path = f"{base_path}/{name_parts[0]}{frame_str}{name_parts[-1]}"
    os.remove(file_path)

Path Utilities

>>> os.path.abspath('document.txt')
'/home/user/documents/document.txt'

>>> os.path.isdir('document.txt')
False
>>> os.path.isdir('documents')
True

>>> os.listdir('/home/user')
['documents', 'images', 'notes.txt']

Counting Text Files

import os

txt_count = 0
for root, dirs, files in os.walk('.'):
    for file_name in files:
        if file_name.endswith('.txt'):
            txt_count += 1
            
print(f'Text files: {txt_count}')

Command-Line Arguments

import sys

print(f'Arguments count: {len(sys.argv)}')
for i, arg in enumerate(sys.argv):
    print(f'Argument {i}: {arg}')

Process Execution

import os

command = 'ls -l'
process = os.popen(command)
output = process.read()
status = process.close()
print(f"Exit status: {status}")

Web Data Extraction

import urllib.request
from bs4 import BeautifulSoup

url = input("Enter URL: ")
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')

total = 0
count = 0
for span in soup.find_all('span'):
    value = span.string
    if value:
        count += 1
        total += int(value)
        
print(f"Count: {count}")
print(f"Sum: {total}")

List Comperhension

mixed = [1, 2, 'a', 'b', 3, 'c']
strings = [item.upper() for item in mixed if isinstance(item, str)]
print(strings)

Number Sqeuence Groupign

from itertools import groupby

data = [1, 2, 3, 10, 11, 100, 9999]
grouped = []
for k, g in groupby(enumerate(data), lambda x: x[0]-x[1]):
    group = [item[1] for item in g]
    grouped.append(group)
    
print(grouped)

File Sequence Formatting

import re
import itertools

files = [
    "image_0001", "image_0002", "image_0003",
    "image_0010", "image_0011",
    "image_0011-1", "image_0011-2", "image_0011-3",
    "image_0100", "image_9999"
]

def get_number(name):
    return re.findall(r"\d+", name)[-1]

def format_group(group):
    if len(group) == 1:
        return group[0][1]
    first = get_number(group[0][1])
    last = get_number(group[-1][1])
    prefix = group[0][1].split(first)[0]
    return f"{prefix}[{first}-{last}]"

results = []
for key, group in itertools.groupby(enumerate(files), 
                                   lambda x: x[0] - int(get_number(x[1]))):
    results.append(format_group(list(group)))
    
print(results)

String Formatting

device = {
    'name': "Blender",
    'cores': 160,
    'version': "3.01c",
    'memory': 64,
    'year': 2020
}

print(f"{device['name']} has {device['cores']} cores, "
      f"{device['memory']}GB memory, version {device['version']}, "
      f"releasing in {device['year']}.")

user_info = ["Alex", 35, "Male"]
print("User: {0}, Age: {1}, Gender: {2}".format(*user_info))

print("{0:#^30}\n{1:.^30}".format("", "TITLE"))

for num in range(1, 11):
    print(f"{num:02}{'.'*10}{num}*{num} = {num*num}")

Tags: python filesystem CommandLine WebScraping ListComprehension

Posted on Wed, 29 Jul 2026 16:54:57 +0000 by Mykasoda