Python File Handling Basics: Reading & Writing Files

🐍 𝐃𝐚𝐲 𝟖 (𝐌𝐨𝐫𝐧𝐢𝐧𝐠) 𝐨𝐟 𝐌𝐲 𝟏𝟓-𝐃𝐚𝐲 𝐏𝐲𝐭𝐡𝐨𝐧 𝐂𝐡𝐚𝐥𝐥𝐞𝐧𝐠𝐞 — 𝐅𝐢𝐥𝐞 𝐇𝐚𝐧𝐝𝐥𝐢𝐧𝐠 Today’s morning session was about file handling — how Python reads from and writes to files. File handling is essential for working with logs, reports, CSVs, and data pipelines. 🔹 𝐖𝐡𝐚𝐭 𝐈 𝐂𝐨𝐯𝐞𝐫𝐞𝐝 𝐓𝐨𝐝𝐚𝐲 ✅ Opening & Reading a File file = open("data.txt", "r") content = file.read() file.close() ✅ Using with Statement (Recommended) Automatically closes the file. with open("data.txt", "r") as file: content = file.read() ✅ Writing to a File with open("data.txt", "w") as file: file.write("Learning Python File Handling") ✅ Appending to a File with open("data.txt", "a") as file: file.write("\nNew line added") ✅ Reading Line by Line with open("data.txt") as file: for line in file: print(line.strip()) 🎯 𝐊𝐞𝐲 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 File handling allows Python programs to persist data beyond runtime. Using the with statement ensures cleaner and safer file operations. 🌆 𝐄𝐯𝐞𝐧𝐢𝐧𝐠 𝐒𝐞𝐬𝐬𝐢𝐨𝐧 (𝐃𝐚𝐲 𝟖): 𝐃𝐚𝐭𝐞 & 𝐓𝐢𝐦𝐞 𝐇𝐚𝐧𝐝𝐥𝐢𝐧𝐠 Let’s keep learning #Python #FileHandling #15DaysOfPython #LearningInPublic #Programming

To view or add a comment, sign in

Explore content categories