Python Programming
Working with Files
Introduction
- Programs often need to save or read data from files. Python makes this simple!
- You can work with text files, CSV files, JSON files, and more.
Reading Text Files
- “`python
- # Read entire file
- file = open('data.txt', 'r') # 'r' means read mode
- content = file.read()
- print(content)
- file.close()
- “`
- Better way (automatically closes file):
- “`python
- with open('data.txt', 'r') as file:
- content = file.read()
- print(content)
- “`
Writing to Files
- “`python
- with open('output.txt', 'w') as file: # 'w' means write mode
- file.write('Hello, World!n')
- file.write('Python is awesome!')
- “`
- Append to Existing File:
- “`python
- with open('output.txt', 'a') as file: # 'a' means append
- file.write('nAdding new line')
- “`
Working with CSV Files
- CSV (Comma Separated Values) files are common for storing data:
- “`python
- import csv
- # Reading CSV
- with open('students.csv', 'r') as file:
- reader = csv.reader(file)
- for row in reader:
- print(row)
- # Writing CSV
- with open('output.csv', 'w', newline='') as file:
- writer = csv.writer(file)
- writer.writerow(['Name', 'Age', 'Grade'])
- writer.writerow(['Ahmed', 20, 'A'])
- “`
Working with JSON
- JSON is used to store structured data (like dictionaries):
- “`python
- import json
- # Save data to JSON
- student = {'name': 'Ali', 'age': 22, 'grade': 'A'}
- with open('student.json', 'w') as file:
- json.dump(student, file)
- # Read JSON
- with open('student.json', 'r') as file:
- data = json.load(file)
- print(data['name'])
- “`
Real Example: Contact Book
- “`python
- import json
- def save_contact(name, phone):
- contacts = []
- try:
- with open('contacts.json', 'r') as file:
- contacts = json.load(file)
- except:
- pass # File doesn't exist yet
- contacts.append({'name': name, 'phone': phone})
- with open('contacts.json', 'w') as file:
- json.dump(contacts, file)
- save_contact('Ahmed', '0300-1234567')
- “`