Zum Hauptinhalt springen
Intelligence View
⚡ tsecurity.de Intelligence

Python for Beginners — Part 7: Modules, Errors & Files

Part 7 of a beginner-friendly series on learning Python from scratch. In Part 6, we learned to write reusable functions. Now it's time to make those functions…

Beitrag
0
Seite
0
↗ Quelle (dev.to)
Quelle & Fakten · 7 Min. Lesezeit
Quelle: dev.to
Rubrik: Sichere Programmierung

Part 7 of a beginner-friendly series on learning Python from scratch.



In Part 6, we learned to write reusable functions. Now it's time to make those functions work in the real world: reading data from files, handling things when they go wrong, and using code other people have written.



This is where Python transitions from "learning exercises" to "actual programs." Real programs read files, talk to the internet, handle unexpected input, and use libraries to solve complex problems.






Modules and Imports



A module is a file containing Python code that you can reuse. Python comes with a huge standard library of modules, and you can also install external ones.






Using the math module






import math

print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
print(math.pi) # 3.14159...
print(math.ceil(4.3)) # 5 (round up)
print(math.floor(4.7)) # 4 (round down)






import math loads the math module. You access its functions and constants with dot notation: math.sqrt(), math.pi, etc.






Importing specific items



If you only need a few things, import them directly:




from math import sqrt, pi

print(sqrt(16)) # 4.0 (no need for math.)
print(pi) # 3.14159...






Now you use sqrt() directly, not math.sqrt().






Aliasing imports



Use as to give a module a shorter name:




import math as m

print(m.sqrt(16)) # 4.0






Or alias specific items:




from math import sqrt as square_root

print(square_root(16)) # 4.0









Working with datetime



The datetime module is essential for handling dates and times:




from datetime import datetime, timedelta

# Get current date and time
now = datetime.now()
print(now) # 2024-06-23 14:30:45.123456

# Create a specific date
birthday = datetime(1999, 5, 15)
print(birthday) # 1999-05-15 00:00:00

# Format as string
print(now.strftime("%Y-%m-%d")) # 2024-06-23
print(now.strftime("%A, %B %d")) # Sunday, June 23

# Time differences
future = now + timedelta(days=30)
print(future) # Date 30 days from now









Working with JSON



JSON (JavaScript Object Notation) is a standard format for exchanging data. Python dictionaries map perfectly to JSON:




import json

# Convert Python dict to JSON string
person = {
"name": "Ramesh",
"age": 25,
"city": "Chennai",
"hobbies": ["reading", "coding", "gaming"]
}

json_string = json.dumps(person)
print(json_string)
# {"name": "Ramesh", "age": 25, "city": "Chennai", "hobbies": ["reading", "coding", "gaming"]}

# Convert JSON string back to Python dict
parsed = json.loads(json_string)
print(parsed["name"]) # Ramesh






Reading and writing JSON files:




import json

# Write to file
data = {"name": "Ramesh", "age": 25}
with open("data.json", "w") as file:
json.dump(data, file)

# Read from file
with open("data.json", "r") as file:
data = json.load(file)
print(data)









Regular Expressions (Regex)



Regex is a language for pattern matching in text. It's powerful but takes time to master. Here are common patterns:




import re

text = "My phone is 555-1234 and email is [email protected]"

# Find a pattern
phone = re.search(r"\d{3}-\d{4}", text)
if phone:
print(phone.group()) # 555-1234

# Find all matches
emails = re.findall(r"[\w.-]+@[\w.-]+\.\w+", text)
print(emails) # ['[email protected]']

# Replace
cleaned = re.sub(r"\d", "X", text)
print(cleaned) # Phone is XXX-XXXX...

# Check if pattern matches
if re.match(r"^\d+$", "12345"):
print("It's all digits")






Regex patterns (a few common ones):





  • \d — any digit (0-9)


  • \w — any word character (letter, digit, underscore)


  • \s — any whitespace


  • . — any character


  • * — zero or more


  • + — one or more


  • ? — zero or one


  • {n} — exactly n times


  • ^ — start of string


  • $ — end of string


  • [abc] — a, b, or c



Regex is complex; this is just an introduction. Most beginners use regex sparingly and look up patterns when needed.






File Input and Output






Reading files






# Simple read
with open("myfile.txt", "r") as file:
content = file.read()
print(content)

# Read line by line
with open("myfile.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes newline

# Read all lines as a list
with open("myfile.txt", "r") as file:
lines = file.readlines()
print(lines[0]) # First line






The with statement is crucial — it automatically closes the file when you're done, even if an error occurs.






Writing files






# Write (overwrites if file exists)
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Second line\n")

# Append (add to end of file)
with open("output.txt", "a") as file:
file.write("Third line\n")









Working with file paths






import os

# Check if file exists
if os.path.exists("myfile.txt"):
print("File found")

# Get file size
size = os.path.getsize("myfile.txt")
print(f"File size: {size} bytes")

# List files in directory
files = os.listdir(".")
print(files)

# Create directory
os.makedirs("my_folder", exist_ok=True)

# Delete file
os.remove("myfile.txt")









Exception Handling



Real programs fail sometimes — bad file paths, network errors, invalid input. Handle these gracefully with try/except:




try:
# Code that might fail
number = int("not a number")
except ValueError:
print("That's not a valid number")






If int() fails, Python catches the ValueError and runs the except block instead of crashing.






Multiple exceptions






try:
file = open("missing.txt", "r")
number = int(file.read())
except FileNotFoundError:
print("File doesn't exist")
except ValueError:
print("File contains non-numeric data")
except Exception as e:
print(f"Something went wrong: {e}")






Handle specific errors first, then generic ones. Exception catches everything.






Try, except, else, finally






try:
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
print("File not found")
else:
# Runs if no exception occurred
print(f"Successfully read {len(data)} characters")
finally:
# Always runs, useful for cleanup
print("Done")








  • try — code that might fail


  • except — what to do if it fails


  • else — what to do if it succeeds


  • finally — always runs (cleanup)






Raising exceptions



You can raise exceptions yourself:




def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return True

try:
validate_age(-5)
except ValueError as e:
print(f"Invalid input: {e}")









Installing External Libraries with pip



The pip package manager lets you install libraries others have written:




pip install requests      # Install the requests library
pip install numpy pandas # Install multiple packages
pip install requests==2.28.0 # Install specific version
pip list # Show installed packages
pip uninstall requests # Remove a package






Once installed, use them like built-in modules:




import requests

response = requests.get("https://api.github.com")
print(response.status_code) # 200






Popular libraries for beginners:





  • requests — make web requests


  • numpy — numerical computing


  • pandas — data analysis


  • matplotlib — plotting and visualization


  • flask — build web applications






Practical Examples






Example 1: Read and count words






def count_words(filename):
try:
with open(filename, "r") as file:
content = file.read()
words = content.split()
return len(words)
except FileNotFoundError:
print(f"Error: {filename} not found")
return 0

count = count_words("myfile.txt")
print(f"Total words: {count}")









Example 2: Save and load JSON data






import json

def save_contacts(contacts, filename):
with open(filename, "w") as file:
json.dump(contacts, file, indent=2)

def load_contacts(filename):
try:
with open(filename, "r") as file:
return json.load(file)
except FileNotFoundError:
return []

# Save
contacts = [
{"name": "Ramesh", "phone": "555-1234"},
{"name": "Priya", "phone": "555-5678"}
]
save_contacts(contacts, "contacts.json")

# Load
loaded = load_contacts("contacts.json")
print(loaded)









Example 3: Extract data with regex






import re

def extract_emails(text):
pattern = r"[\w.-]+@[\w.-]+\.\w+"
return re.findall(pattern, text)

text = "Contact me at [email protected] or [email protected]"
emails = extract_emails(text)
print(emails) # ['[email protected]', '[email protected]']









Why This Matters



File I/O and exception handling are what separate learning exercises from real programs. Every professional program reads data from files or the internet, handles errors gracefully, and uses external libraries. Modules let you leverage thousands of hours of other people's work instead of writing everything yourself.



The most common beginner mistakes:




  • Forgetting to close files (use with — it's mandatory style)

  • Not handling file not found errors

  • Assuming regex patterns are simpler than they are

  • Catching generic Exception instead of specific errors

  • Not installing libraries with pip correctly






What's Next



In Part 8, the final part, we'll explore object-oriented programming — classes, inheritance, and polymorphism. OOP is how professional Python code is structured, and everything you've learned so far will come together.






This is Part 7 of an 8-part beginner Python series. Catch up on Part 1: Getting Started & Syntax, Part 2: Variables, Data Types & Numbers, Part 3: Strings & Booleans, Part 4: Operators & Control Flow, Part 5: Collections, and Part 6: Functions.

Social ReaktionenReagiere als Erste:r — dein Feedback zählt!
Informations-Bewertung:
✏️ Information ergänzen
🛡️ Versioniert via CMS-Revisions-Engine (Freigabe-Queue für Gäste)

💬 Community-Diskussion & Kommentare

🌐 Zum Hauptchat

Starte die Diskussion im Social-Chat Broadcast Stream oder reiche oben über „Information ergänzen“ einen Fachbeitrag ein.

Security Briefing Kostenlos · 1-Klick-Abmeldung

Intelligence Digest — kostenlos

Täglich die wichtigsten Security-News · jederzeit abbestellbar

Community Rating &amp; Social Proof
⭐ Leser-Wertung
–
Ø / 5.0
Noch keine Leser-Bewertungen
War dieser Artikel hilfreich?
0
Jetzt Bewertung abgeben
Detail-Bewertung (optional)
Inhalt & Qualität
Quelle & Glaubwürdigkeit
Aktualität

Verwandte Story-Cluster & Quellen (Vektor-KI)

6 Cluster
21 Quellen
AI-Powered Black Friday Scams Raise Enterprise Security Risks
eSecurityPlanet vor 41 Min.
20 weitere Quellen
Latest from TechRadarvor 36 Min.'A Thunderbolt 5 docking station with more ports and features than you'll know what to do with': Connect everything with the feature-packed Ugreen Maxidok 17-in-1 Dock on sale for Black Friday Cult of Macvor 41 Min.The best Black Friday deals to upgrade your iPhone, iPad and Mac setup Latest from TechRadarvor 1 Std.Black Friday 2026 laptop deals: top offers on Chromebooks, MacBooks, Windows 11 laptops and more CNETvor 1 Std.This Black Friday Deal Will Save You $310 on a Chefman Indoor Pizza Oven netzwelt.devor 2 Std.Betrugsanruf oder echter Paketdienst? So schützt ihr euch beim Online-Shopping - zum Black Friday spart ihr 75 Prozent bei Norton 360 Advanced netzwelt.devor 1 Std.Den besten Telekom-Tarif am Black Friday gibt es wieder, aber es gibt eine Haken PC-WELTvor 59 Min.Amazon Black Friday Woche: Die besten Technik-Deals im Überblick Latest from TechRadarvor 1 Std.Newegg knocks $200 off the 4TB KingSpec P3 SATA SSD for Black Friday CNETvor 19 TagenGTA 6 May Not Be on Sale, but These Black Friday PlayStation Deals Are Still Worth Shopping The Vergevor 1 Std.Dreame and Eufy are offering nearly 60 percent off robovacs for Black Friday Latest from TechRadarvor 1 Std.Black Friday Roku deals: save on Roku Streaming Sticks, Roku TVs, and more Computer Bildvor 1 Std.Bigbank erhöht Festgeldzinsen: Bis zu 3,60 Prozent zum Black Friday Golem.devor 1 Std.Anzeige: 65 Zoll großer OLED-TV von Samsung günstig wie nie am Black Friday Latest from TechRadarvor 3 Std.Black Friday Pixel deals: save big on Pixel 10, Pixel 10a, Pixel 11 Pro, and more Latest from TechRadarvor 3 Std.Samsung's Black Friday sale is here — I've found 11 excellent deals, including up to $1,800 off OLED TVs, Galaxy S26 Ultra, tablets, and more Latest from TechRadarvor 3 Std.Pick your favourite shade: every AeroPress colour is on sale for Black Friday Latest from TechRadarvor 2 Std.PureVPN has launched 5-year plans just in time for Black Friday — $1.49 per month for half a decade of protection Latest from TechRadarvor 2 Std.DDR5 RAM Black Friday deals: 6 32GB kits under $500 — because sadly that’s where memory prices are right now Latest from TechRadarvor 2 Std.25 hand-picked deals in the Amazon UK Black Friday sale — Lego, Bose earbuds, Switch 2, Ninja Crispi, Kindles, and more heise online Newsvor 1 TagBlack Friday 2026: Die besten Deals für Smartphones, Tablets und Smartwatches
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Python for Beginners — Part 7: Modules, Errors & Files

Thematisch verwandte Begriffe: Python, Beginners, Part, Modules · 6 Treffer

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

💬 Kommentare werden geladen…
Zum Aktualisieren ziehen
Widgets & Themen
Widgets werden geladen…
Nächster Beitrag