0% found this document useful (0 votes)
14 views

python start lecture 13

The document covers recursion in Python, explaining its definition, base case, and recursive case, along with practical examples like fractal trees and the Tower of Hanoi. It also details file handling, including types of files, modes for opening files, reading and writing methods, and exception handling. Additionally, it introduces JSON, its structure, and how to convert Python data to JSON and vice versa.

Uploaded by

Aisulu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

python start lecture 13

The document covers recursion in Python, explaining its definition, base case, and recursive case, along with practical examples like fractal trees and the Tower of Hanoi. It also details file handling, including types of files, modes for opening files, reading and writing methods, and exception handling. Additionally, it introduces JSON, its structure, and how to convert Python data to JSON and vice versa.

Uploaded by

Aisulu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Python – continue recursion,

file handling, json


Week 7 lecture (2)
Quick Recap
● Definition: A function that calls itself
● Base Case: Stops recursion to prevent infinite calls
● Recursive Case: Function calls itself with a smaller problem
Recursion
practice time!
● fractal tree
● tower of hanoi
01
File Handling
Why Use Files?
📂 Store data permanently (unlike variables,
which disappear when a program stops).
📄 Read/write data from .txt or .csv
(and more) files.
Types of Files
📄 Text Files (.txt, .csv, .json)
● Stores human-readable data (UTF-8, ASCII).
● Examples: Logs, config files, structured data (CSV,
JSON).
📦 Binary Files (.bin, .jpg, .mp3)
● Stores data in raw binary format (not human-readable).
● Examples: Images, videos, audio, compiled programs.
Opening a File
🔹 Use the open() function:
file = open("data.txt", "r")
# Open in read mode
Modes in open():

Mode Meaning
"r" Read (default), error if file doesn’t exist

"w" Write (creates a new file or overwrites existing content)

"a" Append (adds to the end of a file)

"x" Create (fails if file already exists)

"r+" Read and write

"wb" Write binary

"rb" Read binary


Reading a File
Three ways to read a file:

# Read full content


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

# Read line by line


with open("data.txt", "r") as file:
for line in file:
print(line.strip()) # Removes \n

# Read into a list


with open("data.txt", "r") as file:
lines = file.readlines() # List of lines

✅ Best practice: Use with open(...) to auto-close files.


Slide 5: Writing to a File
🔹 Using "w" mode will
with open("output.txt", "w") as file: overwrite existing content.
file.write("Hello, world!\n") 🔹 To add new content instead,
file.write("Abobus. :P") use "a" (append mode).

📌 Difference between w and a:

with open("output.txt", "a") as file: ● "w" clears the file before


file.write("\nThis is a new line.") writing.
● "a" keeps the existing
content and adds new data.
Exception Handling with Files
❌ What if the file doesn’t exist?
✅ Use try-except for error handling:

try:
with open("nonexistent.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
0
2
JSON in Python
What is JSON?
📊 JSON (JavaScript Object Notation) = A lightweight
data format for storing structured data.
💡 Looks like a Python dictionary:
{
"name": "Alice",
"age": 25,
"city": "New York"
}
🔹 Used in APIs, config files, databases.
Converting Python Data to JSON
Python dictionary → JSON string:

import json
data = {"name": "Abobus", "age": 25}
json_string = json.dumps(data, indent = 4) # Pretty-printing
print(json_string)

📌 indent = 4 makes JSON readable.

Writing JSON to a File

with open("data.json", "w") as file:


json.dump(data, file, indent=4)

📝 json.dump() writes directly to a file.


Reading JSON from a File
# data = {"name": "Abobus", "age": 25}
with open("data.json", "r") as file:

loaded_data = json.load(file)

print(loaded_data["name"]) # Abobus

🔹 json.load() converts JSON file → Python dictionary.


Practice time!
Спасибо!

You might also like