Repository navigation
Expand file tree
/
Copy pathfile_handling_exercises.py
More file actions
74 lines (58 loc) · 2.34 KB
/
Copy pathfile_handling_exercises.py
File metadata and controls
74 lines (58 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# ==========================================
# Python Learning Lab: 07 File Handling
# ==========================================
import os
import json
print("--- Running File Handling Exercises ---")
# Setup folder variables
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
TEXT_FILE = os.path.join(CURRENT_DIR, "test_file.txt")
JSON_FILE = os.path.join(CURRENT_DIR, "test_data.json")
# ==========================================
# Challenge 1: Write and Read Text File
# ==========================================
# Write the string "Python File Handling" to a file named `TEXT_FILE`.
# Then, open the file, read the contents, and verify it matches.
def write_and_read():
# TODO: Open TEXT_FILE in write mode and write text.
# Use context manager: with open(...) as f:
with open(TEXT_FILE, "w") as f:
f.write("Python File Handling")
# TODO: Open TEXT_FILE in read mode and read text.
with open(TEXT_FILE, "r") as f:
content = f.read()
return content
# --- Verification ---
result_text = write_and_read()
assert os.path.exists(TEXT_FILE), "File was not created"
assert result_text.strip() == "Python File Handling", f"Expected 'Python File Handling', got '{result_text}'"
print("✓ Challenge 1 passed!")
# ==========================================
# Challenge 2: JSON Handling
# ==========================================
# Dump the `user_profile` dictionary as JSON to `JSON_FILE`.
# Then, read it back from `JSON_FILE` and load it into a Python dictionary.
user_profile = {
"username": "ritshea",
"course": "Python",
"is_active": True
}
def json_operations():
# TODO: Write user_profile to JSON_FILE using json.dump()
with open(JSON_FILE, "w") as f:
json.dump(user_profile, f)
# TODO: Read JSON_FILE and parse it using json.load()
with open(JSON_FILE, "r") as f:
loaded_dict = json.load(f)
return loaded_dict
# --- Verification ---
loaded_profile = json_operations()
assert os.path.exists(JSON_FILE), "JSON file was not created"
assert loaded_profile == user_profile, f"Parsed JSON dictionary doesn't match original. Got {loaded_profile}"
print("✓ Challenge 2 passed!")
# Clean up test files
if os.path.exists(TEXT_FILE):
os.remove(TEXT_FILE)
if os.path.exists(JSON_FILE):
os.remove(JSON_FILE)
print("\n🎉 All tests passed successfully (and clean-up completed)!")