File Handling

โœ•

1. ๐Ÿ“ File Handling

    1.1 What is File Handling?
    1. 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.
    1.2 Why Use File Handling?
    1. 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
    1.3 Types of Files Covered
    1. 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.

2. ๐Ÿ“‚ Opening Files

    2.1 open() Function
    1. 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.
ModeDescriptionNote
'r'Read mode - Opens a file for readingRaises an error if the file does not exist
'w'Write mode - Opens a file for writingCreates a new file if it does not exist; overwrites old content if the file already exists
'a'Append mode - Opens a file for appendingCreates a new file if it does not exist; adds new content at the end of the file
    2.3 Why Close Files?
    1. 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()
    2.4 Context Manager
    1. 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 the with block ends. ๐Ÿ“Œ For the rest of this note, we will use context manager for file operations.

3. ๐Ÿ“ Text Files

    3.1 What is a Text File?
    1. A text file stores human-readable data. Text files usually have .txt extension. Example: notes.txt Text files can store: - Notes - Essays - Logs - Simple records - Plain text data
    3.2 Reading Text Files using read()
    1. 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) ๐Ÿ“Œ Use read() when you want to read the full content of a file.
    3.3 readline() and readlines()
    1. 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)
    3.4 Reading File Line by Line
    1. We can also read a file line by line using a for loop. 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.
    3.5 Writing Text Files using write()
    1. 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?") โš ๏ธ w mode overwrites old content if the file already exists.
    3.6 Writing Multiple Lines using writelines()
    1. 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 \n if we want a new line.
    3.7 Appending Text Files
    1. 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.") ๐Ÿ“Œ a mode does not remove old content. ๐Ÿ“Œ It adds new content at the end of the file.

4. ๐Ÿ“Š CSV Files

    4.1 What is a CSV File?
    1. 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,Grade Ram,20,A Sita,21,B Python provides the csv module to read and write CSV files. ๐Ÿ“Œ CSV data is plain text, but it can be opened in spreadsheet apps like Excel.
    4.2 Reading CSV using csv.reader()
    1. 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.
    4.3 Reading CSV using csv.DictReader()
    1. 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.
    4.4 Writing CSV using csv.writer()
    1. 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.
    4.5 Writing CSV using csv.DictWriter()
    1. 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) ๐Ÿ“Œ fieldnames defines the column names. ๐Ÿ“Œ writeheader() writes the header row.

5. ๐Ÿงพ JSON Files

    5.1 What is JSON?
    1. 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 json module to read and write JSON data.
    5.2 JSON Examples
    1. 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 lowercase true, false, and null. ๐Ÿ“Œ Python uses True, False, and None.
    5.3 JSON and Python Data
    1. 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"]

6. ๐Ÿ”„ Serialization and Deserialization

    6.1 What is Serialization?
    1. 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.
    6.2 What is Deserialization?
    1. 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.
    6.3 dumps(), loads(), dump(), and load()
    1. 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() and loads() work with strings. ๐Ÿ“Œ dump() and load() work with files.

7. ๐Ÿ“– Reading and Writing JSON Files

    7.1 Reading JSON File
    1. 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) ๐Ÿ“Œ data becomes a Python object, usually a dictionary or list.
    7.2 Writing JSON File
    1. 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 into output.json.
    7.3 Writing Pretty JSON
    1. We can use indent to 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=4 formats JSON with proper spacing.

Practice QuestionsNot started

  1. 1. Text Files

    Question 1 of 3

      1.1 Practice text file tasks:
      1. Create a text file python.txt on your desktop and write a short essay about Python in it.
      2. Open this file python.txt. Add the text "I will learn Error Handling Next" at the end.
      3. Create a new file java.txt. Copy the content of python.txt to java.txt but replace the text "Python" or "python" with "Java".
      4. Calculate and display the size of python.txt and java.txt in KB. Hint: Use os module and AI if needed.
      5. Challenge: Read file nobel_prize_speech.txt and display the most repeated word in it.
  2. 2. CSV Files

    Question 2 of 3

      2.1 Practice CSV file tasks:
      1. Create a CSV file std_1.csv with columns: Name, Age, Grade. Add 5 records to it using list of lists.
      2. Create a CSV file std_2.csv with columns: Name, Age, Grade. Add 5 records to it using list of dictionaries.
      3. Read file 2022-01-03.csv and display records as list of lists.
      4. Read file 2022-01-03.csv and display records as list of dictionaries.
  3. 3. JSON Files

    Question 3 of 3

      3.1 Practice JSON file tasks:
      1. 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 named info.json.
      2. Load info.json file. 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 in info.csv file.
      3. Read file election_result.json. Find the name of the winner, associated party, and votes obtained.
      4. Read file election_result.json. Find total votes cast and average votes per candidate.
      5. Convert the file election_result.json into CSV format and save it as election_result.csv.