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)

💬 Dyskusja społeczności i komentarze

🌐 Dołącz do głównego czatu

Rozpocznij dyskusję w strumieniu transmisji Social Chat lub prześlij wyżej wkład ekspercki przez formularz uzupełnień.

Security Briefing Bezpłatnie · Wypisanie 1 kliknięciem

Intelligence Digest - bezpłatnie

Codziennie najważniejsze wiadomości bezpieczeństwa · można pobrać w każdej chwili

Community Rating &amp; Social Proof
⭐ Ocena czytelników
–
Ø / 5.0
Brak recenzji czytelników
Czy ten artykuł był pomocny?
0
Dodaj swoją ocenę
Ocena szczegółowa (opcjonalnie)
Treść i jakość
Źródło i wiarygodność
Aktualność

Powiązany klaster opowieści i źródła (wektor AI)

1 Cluster
Podobne wkłady
🔍 Verwandte News

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

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

Laden...

Filmy są załadowane...

Laden...

Składki są załadowane...

Laden...

Filmy są załadowane...

Laden...

Składki są załadowane...

Laden...

Filmy są załadowane...

Laden...

Składki są załadowane...

Laden...

Filmy są załadowane...

Laden...

Składki są załadowane...

Laden...

Filmy są załadowane...

Uwagi Komentarze są ładowane..
Rysunek do aktualizacji
Widgets & Topics
Loading widgets…
Nächster Beitrag