File Handling
✕Introduction
- Process of working with files in Python
- Python provides built-in functions for reading and writing files
- In any operation we open file, read/write and then close (critical due to lock)
- Context manager is used to automatically close file after operation is done
- Text Files (.txt) - Store data in human-readable format
- CSV Files (.csv) - Store tabular data in comma-separated values
- JSON Files (.json) - Store data in JavaScript Object Notation format
Types Of File Covered
Opening Files
open()function is used to open a file that returns a file object- Syntax:
open(filename, mode, encoding) - Encoding is important for text files to ensure correct character representation
| Mode | Description | Note |
|---|---|---|
| 'r' | Read mode (default) - Opens file for reading | raises error if file does not exist |
| 'w' | Write mode - Opens file for writing | creates a new file (overwrites if file exists) |
| 'a' | Append mode - Opens file for appending | creates file if it does not exist |
File Opening Modes in Python
Text File
- Normally used for storing human-readable data.
- We need to read and write text files.
- Use
read()method to read the entire file - Use
readlines()method to read all lines in a list - Use
write()method to write a string to a file - Use
writelines()method to write a list of strings to a file
Reading Text Files
Writing Text Files
Reading Text Files
file_obj = open("sample.txt", "r")content = file_obj.read()print(content)file_obj.close()with open("sample.txt", "r") as file_obj:content = file_obj.read()# Try withreadline()andreadlines()print(content)
Approach 1:
Approach 2 (Preferred):
Writing Text Files
- For rest, we will use context manager to handle file operations.
with open("output.txt", "w") as file_obj:file_obj.write("Hello, World!\n")file_obj.write("How are you?")data_list = ["I am 'Rabindra'\n", "I am learning Python\n", "Bye\n"]with open("output.txt", "w") as file_obj:file_obj.writelines(data_list)# Did you notice old data is overwritten?
Example:
Reading CSV Files
- Python provides
csvmodule to read and write CSV files import csvwith open("data.csv", "r") as file_obj:csv_reader = csv.reader(file_obj)data = list(csv_reader)print(data)# List of rows, where each row is a list of valuesimport csvwith open("data.csv", "r") as file_obj:csv_reader = csv.DictReader(file_obj)data = list(csv_reader)print(data)# List of dictionaries, where each dictionary represents a row
Example:
Writing CSV Files
import csvdata = [["Name", "Age"], ["Rabindra", 30], ["Hari", 25]]with open("output.csv", "w", newline="") as file_obj:csv_writer = csv.writer(file_obj)csv_writer.writerows(data)import csvdata = [{"Name": "Rabindra", "Age": 30}, {"Name": "Hari", "Age": 25}]with open("output.csv", "w", newline="") as file_obj:fieldnames = ["Name", "Age"]csv_writer = csv.DictWriter(file_obj, fieldnames=fieldnames)csv_writer.writeheader()csv_writer.writerows(data)
Example:
JSON Files
- JavaScript Object Notation is a lightweight data-interchange format
- Easily to read for human and parse for machines
- Equivalent to Python dictionaries
- Python provides
jsonmodule to read and write JSON files {"name": "Rabindra", "age": 30}{"country": "Napal", "cities": ["Kathmandu", "Pokhara", "Lalitpur"]}{"name": "Ram", "age": 27, "is_student": false, "courses": ["Python", "JS"]}
JSON Example:
Serialization and Deserialization
- Serialization => Converting a Python object into a JSON string
- Deserialization => Converting a JSON string back into a Python object
import jsondata = {"name": "Rabindra", "age": 30}json_string = json.dumps(data)print(json_string)# Check data type of data and json stringimport jsonjson_string = '{"name": "Rabindra", "age": 30}'data = json.loads(json_string)print(data["name"])# Check datatype of json string and data
Serialization Example:
Deserialization Example:
Reading and Writting JSON Files
import jsonwith open("data.json", "r") as file_obj:data = json.load(file_obj)print(data)# Python object (dict or list)import jsondata = {"name": "Python", "duration": 30}with open("output.json", "w") as file_obj:json.dump(data, file_obj)
Reading Json File
Writing Json File
