File Handling in Python
Bodhisattwa Das
Freelancing Brand Strategist & Consultant || Guiding Freelancers to start their journey || Empowering 12k+ Learners as Udemy Instructor || Lifelong Learner & Solopreneur.
File Handling in Python: Your Gateway to Data Storage and Exchange
Python's prowess extends beyond computation; it also empowers you to interact with files, unlocking a world of possibilities for data storage, analysis, and exchange. Whether you're working with plain text, structured CSV files, or the flexible JSON format, Python provides a streamlined approach to handling it all.
Why File Handling?
Files are essential for persisting data beyond the lifetime of your program. They allow you to:
Reading and Writing Files
Python's built-in open() function is your gateway to file interactions:
# Writing to a File
with open("data.txt", "w") as file:
file.write("Hello from Python!\n")
# Reading from a File
with open("data.txt", "r") as file:
content = file.read()
print(content)
Key points:
领英推荐
Working with CSV Files
CSV (Comma-Separated Values) files are widely used for storing tabular data. Python's csv module simplifies working with CSV files:
import csv
# Reading a CSV File
with open("grades.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
# Writing to a CSV File
data = [["Name", "Grade"], ["Alice", 95], ["Bob", 88]]
with open("new_grades.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
Handling JSON Data
JSON (JavaScript Object Notation) is a popular, human-readable format for exchanging data. Python's json module makes JSON a breeze:
import json
# JSON Data
data = {"name": "Alice", "age": 30, "city": "New York"}
# Writing to a JSON File
with open("data.json", "w") as file:
json.dump(data, file)
# Reading from a JSON File
with open("data.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data["name"])
Error Handling and Best Practices
Embrace the Power of Files
File handling unlocks a world of data-driven possibilities. By mastering these techniques, you'll be equipped to build applications that store, retrieve, and transform information in ways that elevate your Python projects to new heights.
Happy coding!