Skip to content
Laviyx Learn

Try

Python course menu

Useful Python Scripts for Everyday Tasks (With Full Code)

Small, practical Python scripts you can use and adapt: a secure password generator, word frequency counter, duplicate file finder, folder size reporter, currency converter, and a command-line tool with argparse.

Intermediate7 min readUpdated
On this page

The best way to cement what you have learned is to build small tools you actually use. Each script below is short, uses only the standard library, and combines several ideas from the course. Copy them, run them, and then change them to fit your own needs.

1. Secure password generator#

Python
import secrets
import string

def make_password(length=12):
    alphabet = string.ascii_letters + string.digits + "!@#$%"
    while True:
        pwd = "".join(secrets.choice(alphabet) for _ in range(length))
        if (any(c.islower() for c in pwd)
                and any(c.isupper() for c in pwd)
                and any(c.isdigit() for c in pwd)):
            return pwd

p = make_password(16)
print(p)
print(len(p), any(c.isdigit() for c in p), any(c.isupper() for c in p))

The password itself is different every time, for example k7#Qm2XpL9!vRt4a. The checks always print:

Output
16 True True

Uses: string constants, generator expressions, any(), while True with return.

2. Word frequency counter#

Python
import re
from collections import Counter

text = """Python is easy to learn. Python is also powerful.
Many people learn Python as their first language."""

words = re.findall(r"[a-z']+", text.lower())
common = Counter(words).most_common(3)
print(len(words), common)
Output
17 [('python', 3), ('is', 2), ('learn', 2)]

Point it at a file with Path("essay.txt").read_text() to analyse your own writing.

Uses: regular expressions, Counter, string methods.

3. Duplicate file finder#

Files with identical content have identical hashes, even if their names differ:

Python
import hashlib
from pathlib import Path

def find_duplicates(folder):
    seen = {}
    for f in sorted(Path(folder).rglob("*")):
        if not f.is_file():
            continue
        digest = hashlib.sha256(f.read_bytes()).hexdigest()
        if digest in seen:
            print(f"{f.name} duplicates {seen[digest]}")
        else:
            seen[digest] = f.name

find_duplicates("files")

With a.txt, b.txt and copy-of-a.txt (a copy of a.txt) in the folder:

Output
copy-of-a.txt duplicates a.txt

The script only reports duplicates; deleting is left to you on purpose. For very large files, read them in chunks rather than all at once.

Uses: pathlib.rglob, dictionaries, hashlib.

4. Folder size reporter#

Python
from pathlib import Path

def human(n):
    for unit in ["B", "KB", "MB", "GB"]:
        if n < 1024:
            return f"{n:.1f} {unit}"
        n /= 1024
    return f"{n:.1f} TB"

def folder_size(folder):
    return sum(f.stat().st_size for f in Path(folder).rglob("*") if f.is_file())

total = folder_size("proj")
print(total, human(total))

For a folder containing a 1,500-byte file and a 2,600-byte file:

Output
4100 4.0 KB

Uses: generator expressions with sum(), loops with early return, f-string formatting.

5. Currency converter#

Python
def convert(amount, rate):
    return round(amount * rate, 2)

rates = {"USD": 0.012, "EUR": 0.011}   # example rates per rupee
for cur, rate in rates.items():
    print(f"₹1,000 = {convert(1000, rate)} {cur}")
Output
₹1,000 = 12.0 USD
₹1,000 = 11.0 EUR

These rates are fixed examples. To use live rates, fetch them from a currency API instead of hard-coding them.

6. A real command-line tool with argparse#

argparse turns a script into a proper command-line program with arguments, options and automatic --help:

greet.py (Python)
import argparse

parser = argparse.ArgumentParser(description="Greet someone")
parser.add_argument("name")
parser.add_argument("--times", type=int, default=1)
args = parser.parse_args()

for _ in range(args.times):
    print(f"Hello, {args.name}!")
Terminal
python greet.py Asha --times 2
Output
Hello, Asha!
Hello, Asha!

Running python greet.py --help prints a generated usage message. Add argparse to any of the scripts above to make them reusable from the terminal, for example python dupes.py ~/Downloads.

Project ideas to try next#

IdeaSkills you will practise
Expense tracker that saves to CSVinput, files, dictionaries
To-do list app stored in JSONJSON, functions
Quiz game with scoresloops, conditions, random
Daily weather emailAPIs, smtplib, scheduling
Habit tracker in SQLitedatabases, dates

Common mistakes#

Practice#

Practice exercise

Using the word counter idea, analyse this sentence: print the total number of words, the number of different words, and the two most common words.

Python
text = "the cat and the hat and the bat sat on the mat"
Show hint

re.findall(r"[a-z]+", text.lower()) gives the words; len(set(words)) counts different ones; Counter(words).most_common(2) gives the top two.

Show solution
Python
import re
from collections import Counter

text = "the cat and the hat and the bat sat on the mat"
words = re.findall(r"[a-z]+", text.lower())
print(len(words), len(set(words)), Counter(words).most_common(2))
Output
12 8 [('the', 4), ('and', 2)]

Key takeaway#

Finished this lesson?