Fixed Top Ad (Local Preview)800x90 • Slot 6608427872
File Handling
✕1. 📁 File Handling
- Imagine a notebook. If we want to use information from the notebook, we first open it. Then we read from it or write in it. After finishing, we close it. File handling in Python works in a similar way. File handling is the process of working with files using Python. Python provides built-in functions for reading and writing files. In most file operations, we follow these steps: 1. Open the file 2. Read from or write to the file 3. Close the file 📌 Closing a file is important because an open file may remain locked or may not save changes properly. 📌 A context manager automatically closes the file after the operation is done.
- File handling is useful when we want to: ✅ Store data permanently ✅ Read data from existing files ✅ Save program output into a file ✅ Work with reports, records, and datasets ✅ Exchange data between programs Example scenarios: - Saving student records - Reading a text document - Processing CSV data from Excel - Reading JSON data from an API - Writing output reports
- In this note, we will learn: - Text Files (.txt) - CSV Files (.csv) - JSON Files (.json) Text Files: Store data in human-readable text format. CSV Files: Store table-like data using comma-separated values. JSON Files: Store structured data using key-value pairs and lists.
1.1 What is File Handling?
1.2 Why Use File Handling?
1.3 Types of Files Covered
2. 📂 Opening Files
- The
open()function is used to open a file. It returns a file object. Syntax:open(filename, mode, encoding="utf-8")Here: filename ➜ Name or path of the file mode ➜ Purpose of opening the file encoding ➜ Character encoding used for text Example:file_obj = open("sample.txt", "r", encoding="utf-8")content = file_obj.read()print(content)file_obj.close()📌encoding="utf-8"helps handle text characters correctly.
2.1 open() Function
| Mode | Description | Note |
|---|---|---|
| 'r' | Read mode - Opens a file for reading | Raises an error if the file does not exist |
| 'w' | Write mode - Opens a file for writing | Creates a new file if it does not exist; overwrites old content if the file already exists |
| 'a' | Append mode - Opens a file for appending | Creates a new file if it does not exist; adds new content at the end of the file |
- After working with a file, we should close it. Closing a file is important because:
✅ It releases system resources
✅ It saves pending changes properly
✅ It prevents file locking issues
✅ It avoids unexpected behavior
Example:
file_obj = open("sample.txt", "r", encoding="utf-8")content = file_obj.read()file_obj.close() - A context manager is a preferred way to work with files. It automatically closes the file after the work is done. We use
with open(...)for this. Example:with open("sample.txt", "r", encoding="utf-8") as file_obj:content = file_obj.read()print(content)📌 The file is automatically closed after thewithblock ends. 📌 For the rest of this note, we will use context manager for file operations.
2.3 Why Close Files?
2.4 Context Manager
3. 📝 Text Files
- A text file stores human-readable data. Text files usually have
.txtextension. Example:notes.txtText files can store: - Notes - Essays - Logs - Simple records - Plain text data read()- reads the entire file as one string. Example:with open("sample.txt", "r", encoding="utf-8") as file_obj:content = file_obj.read()print(content)📌 Useread()when you want to read the full content of a file.readline()- reads one line from the file.readlines()- reads all lines and returns them as a list. Example using readline():with open("sample.txt", "r", encoding="utf-8") as file_obj:first_line = file_obj.readline()print(first_line)Example using readlines():with open("sample.txt", "r", encoding="utf-8") as file_obj:lines = file_obj.readlines()print(lines)- We can also read a file line by line using a
forloop. Example:with open("sample.txt", "r", encoding="utf-8") as file_obj:for line in file_obj:print(line)📌 This is useful when working with large text files. write()is used to write a string to a file. Example:with open("output.txt", "w", encoding="utf-8") as file_obj:file_obj.write("Hello, World!\n")file_obj.write("How are you?")⚠️wmode overwrites old content if the file already exists.writelines()is used to write a list of strings to a file. Example:data_list = ["I am Rabindra\n", "I am learning Python\n", "Bye\n"]with open("output.txt", "w", encoding="utf-8") as file_obj:file_obj.writelines(data_list)📌 Each string should include\nif we want a new line.- Append mode is used to add new content at the end of a file.
Example:
with open("output.txt", "a", encoding="utf-8") as file_obj:file_obj.write("\nThis line is added later.")📌amode does not remove old content. 📌 It adds new content at the end of the file.
3.1 What is a Text File?
3.2 Reading Text Files using read()
3.3 readline() and readlines()
3.4 Reading File Line by Line
3.5 Writing Text Files using write()
3.6 Writing Multiple Lines using writelines()
3.7 Appending Text Files
4. 📊 CSV Files
- CSV stands for Comma-Separated Values. Imagine a table in Excel. It has rows and columns. A CSV file stores table-like data in plain text. Each line is a row. Values are usually separated by commas.
Example:
Name,Age,GradeRam,20,ASita,21,BPython provides thecsvmodule to read and write CSV files. 📌 CSV data is plain text, but it can be opened in spreadsheet apps like Excel. csv.reader()reads each row as a list. Example:import csvwith open("data.csv", "r", newline="", encoding="utf-8") as file_obj:csv_reader = csv.reader(file_obj)data = list(csv_reader)print(data)Output example: [["Name", "Age"], ["Rabindra", "30"], ["Hari", "25"]] 📌csv.reader()returns rows as lists.csv.DictReader()reads each row as a dictionary. Column names become dictionary keys. Example:import csvwith open("data.csv", "r", newline="", encoding="utf-8") as file_obj:csv_reader = csv.DictReader(file_obj)data = list(csv_reader)print(data)Output example: [{"Name": "Rabindra", "Age": "30"}, {"Name": "Hari", "Age": "25"}] 📌csv.DictReader()is useful when CSV has headers.csv.writer()writes data from a list of lists. Example:import csvdata = [["Name", "Age"],["Rabindra", 30],["Hari", 25]]with open("output.csv", "w", newline="", encoding="utf-8") as file_obj:csv_writer = csv.writer(file_obj)csv_writer.writerows(data)📌newline=""helps avoid extra blank lines in CSV files.csv.DictWriter()writes data from a list of dictionaries. Example:import csvdata = [{"Name": "Rabindra", "Age": 30},{"Name": "Hari", "Age": 25}]with open("output.csv", "w", newline="", encoding="utf-8") as file_obj:fieldnames = ["Name", "Age"]csv_writer = csv.DictWriter(file_obj, fieldnames=fieldnames)csv_writer.writeheader()csv_writer.writerows(data)📌fieldnamesdefines the column names. 📌writeheader()writes the header row.
4.1 What is a CSV File?
4.2 Reading CSV using csv.reader()
4.3 Reading CSV using csv.DictReader()
4.4 Writing CSV using csv.writer()
4.5 Writing CSV using csv.DictWriter()
5. 🧾 JSON Files
- JSON stands for JavaScript Object Notation. JSON is a lightweight format used to store and exchange data. It is easy for humans to read and easy for machines to parse. JSON data often looks similar to Python dictionaries. Python provides the
jsonmodule to read and write JSON data. - Example 1:
{"name": "Rabindra", "age": 30}Example 2:{"country": "Nepal", "cities": ["Kathmandu", "Pokhara", "Lalitpur"]}Example 3:{"name": "Ram", "age": 27, "is_student": false, "courses": ["Python", "JS"]}📌 JSON uses lowercasetrue,false, andnull. 📌 Python usesTrue,False, andNone. - JSON object is similar to Python dictionary. JSON array is similar to Python list.
Examples:
JSON object:
{"name": "Ram", "age": 20}Python dictionary:{"name": "Ram", "age": 20}JSON array:["Python", "JavaScript", "SQL"]Python list:["Python", "JavaScript", "SQL"]
5.1 What is JSON?
5.2 JSON Examples
5.3 JSON and Python Data
6. 🔄 Serialization and Deserialization
- Serialization means converting a Python object into a JSON string.
Example:
import jsondata = {"name": "Rabindra", "age": 30}json_string = json.dumps(data)print(json_string)print(type(json_string))📌json.dumps()converts a Python object into a JSON string. - Deserialization means converting a JSON string back into a Python object.
Example:
import jsonjson_string = '{"name": "Rabindra", "age": 30}'data = json.loads(json_string)print(data["name"])print(type(data))📌json.loads()converts a JSON string into a Python object. json.dumps()Converts Python object into JSON string.json.loads()Converts JSON string into Python object.json.dump()Writes Python object into JSON file.json.load()Reads JSON file into Python object. 📌dumps()andloads()work with strings. 📌dump()andload()work with files.
6.1 What is Serialization?
6.2 What is Deserialization?
6.3 dumps(), loads(), dump(), and load()
7. 📖 Reading and Writing JSON Files
json.load()is used to read JSON data from a file. Example:import jsonwith open("data.json", "r", encoding="utf-8") as file_obj:data = json.load(file_obj)print(data)📌databecomes a Python object, usually a dictionary or list.json.dump()is used to write Python data into a JSON file. Example:import jsondata = {"name": "Python", "duration": 30}with open("output.json", "w", encoding="utf-8") as file_obj:json.dump(data, file_obj)📌 This writes data intooutput.json.- We can use
indentto make JSON easier to read. Example:import jsondata = {"name": "Python", "duration": 30}with open("output.json", "w", encoding="utf-8") as file_obj:json.dump(data, file_obj, indent=4)📌indent=4formats JSON with proper spacing.
7.1 Reading JSON File
7.2 Writing JSON File
7.3 Writing Pretty JSON
