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
Practice QuestionsNot started
1. Text Files
Question 1 of 3
- Create a text file
python.txton your desktop and write a short essay about Python in it. - Open this file
python.txt. Add the text "I will learn Error Handling Next" at the end. - Create a new file
java.txt. Copy the content ofpython.txttojava.txtbut replace the text "Python" or "python" with "Java". - Calculate and display the size of
python.txtandjava.txtin KB. Hint: Useosmodule and AI if needed. - Challenge: Read file
nobel_prize_speech.txtand display the most repeated word in it.
1.1 Practice text file tasks:- Create a text file
2. CSV Files
Question 2 of 3
- Create a CSV file
std_1.csvwith columns: Name, Age, Grade. Add 5 records to it using list of lists. - Create a CSV file
std_2.csvwith columns: Name, Age, Grade. Add 5 records to it using list of dictionaries. - Read file
2022-01-03.csvand display records as list of lists. - Read file
2022-01-03.csvand display records as list of dictionaries.
2.1 Practice CSV file tasks:- Create a CSV file
3. JSON Files
Question 3 of 3
- Store data of 5 students in a dictionary like this:
{"9843": {"name": "Rabindra", "age": 30, "course": "Python"}, "9844": {"name": "Hari", "age": 25, "course": "Java"}}. Save this data in a file namedinfo.json. - Load
info.jsonfile. Convert the data into a list of dictionaries like this:[{"phone": "9843", "name": "Rabindra", "age": 30, "course": "Python"}, {"phone": "9844", "name": "Hari", "age": 25, "course": "Java"}]. Save the converted data ininfo.csvfile. - Read file
election_result.json. Find the name of the winner, associated party, and votes obtained. - Read file
election_result.json. Find total votes cast and average votes per candidate. - Convert the file
election_result.jsoninto CSV format and save it aselection_result.csv.
3.1 Practice JSON file tasks:- Store data of 5 students in a dictionary like this:
