-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFile_Handling.py
More file actions
159 lines (136 loc) · 4.67 KB
/
Copy pathFile_Handling.py
File metadata and controls
159 lines (136 loc) · 4.67 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# =====================================================================
# FILE: File_Handling.py
# DESCRIPTION: File modes, `with` statements, JSON reading/writing, cursor seek/tell operations, and modern `pathlib`.
#
# SYNTAX QUICK-REFERENCE:
# # Pathlib Paths
# from pathlib import Path
# path = Path("test.txt")
# path.write_text("Hello!")
# content = path.read_text()
#
# # JSON serialization
# import json
# with open("data.json", "w") as f:
# json.dump({"name": "Alice"}, f)
# =====================================================================
# File_Handling.py
# Reference Guide: Writing, Reading, Appending, JSON Handling, and Directory Operations in Python
import os
import json
# ==========================================
# 1. FILE MODES
# ==========================================
# "r" - Read (default) - Error if file not found
# "w" - Write - Creates or overwrites file
# "a" - Append - Adds content to end of file
# "x" - Create - Error if file exists
# "r+" - Read & Write
# "rb" - Read Binary, "wb" - Write Binary
# ==========================================
# 2. READING, WRITING, AND APPENDING
# ==========================================
print("--- 1. WRITING & READING FILE ---")
filename = "scratch_test.txt"
# Writing a file (Old way using open/close)
file = open(filename, "w")
file.write("Hello, World!\n")
file.write("Python File Handling\n")
file.close()
# Reading the file (Best practice: with statement - auto-closes)
with open(filename, "r") as file:
content = file.read()
print("Full file content:")
print(content)
# Reading specific lines
with open(filename, "r") as file:
print(f"readline() (first line): '{file.readline().strip()}'")
file.seek(0) # reset position to beginning
print(f"readlines() list of lines: {file.readlines()}")
print()
# Appending to a file
print("--- 2. APPENDING TO FILE ---")
with open(filename, "a") as file:
file.write("New line appended!\n")
with open(filename, "r") as file:
print(file.read())
print()
# File Positions (seek/tell)
print("--- 3. FILE POSITIONS ---")
with open(filename, "r") as file:
print(f"Read first 5 chars: '{file.read(5)}'")
print(f"Current Position (tell()): {file.tell()}")
file.seek(0) # reset
print(f"After seek(0), read first line: '{file.readline().strip()}'")
print()
# ==========================================
# 3. LISTS & JSON FILES
# ==========================================
print("--- 4. WRITING & READING LISTS ---")
students = ["Alice\n", "Bob\n", "Charlie\n"]
with open("students.txt", "w") as file:
file.writelines(students)
with open("students.txt", "r") as file:
for line in file:
print(f" Student: {line.strip()}")
print()
print("--- 5. JSON HANDLING ---")
student_data = {"name": "Alice", "age": 20, "grade": "A"}
# Write JSON
json_filename = "student.json"
with open(json_filename, "w") as file:
json.dump(student_data, file, indent=4)
# Read JSON
with open(json_filename, "r") as file:
data = json.load(file)
print(f"Parsed JSON - Name: {data['name']}, Age: {data['age']}")
print()
# ==========================================
# 4. EXCEPTION HANDLING IN FILE OPERATIONS
# ==========================================
print("--- 6. SAFE FILE LOADING ---")
try:
with open("missing_file.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("Handled gracefully: The requested file does not exist!")
print()
# ==========================================
# 5. PATHLIB FOR MODERN PATH HANDLING
# ==========================================
print("--- 7. PATHLIB OPERATIONS ---")
from pathlib import Path
# Creating paths
path = Path("scratch_pathlib_test.txt")
# Writing content using pathlib
path.write_text("Hello via pathlib!")
# Reading content using pathlib
content_pathlib = path.read_text()
print(f"Pathlib read: '{content_pathlib}'")
# Path metadata and existence checks
print(f"File exists: {path.exists()}")
print(f"Is it a file? {path.is_file()}")
print(f"File name: {path.name}")
print(f"File suffix: {path.suffix}")
# Cleanup using Path.unlink()
if path.exists():
path.unlink()
print("Deleted pathlib file!")
print()
# ==========================================
# 6. CLEANING UP CREATED FILES & FOLDERS
# ==========================================
print("--- 7. CLEANUP & OS OPERATIONS ---")
# Remove temporary files
for f in [filename, "students.txt", json_filename]:
if os.path.exists(f):
os.remove(f)
print(f"Removed temporary file: {f}")
# Folder Operations
folder_name = "demo_folder"
if not os.path.exists(folder_name):
os.mkdir(folder_name)
print(f"Created directory: {folder_name}")
os.rmdir(folder_name)
print(f"Deleted directory: {folder_name}")
print()