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
  • Types Of File Covered
    1. Text Files (.txt) - Store data in human-readable format
    2. CSV Files (.csv) - Store tabular data in comma-separated values
    3. JSON Files (.json) - Store data in JavaScript Object Notation format

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
ModeDescriptionNote
'r'Read mode (default) - Opens file for readingraises error if file does not exist
'w'Write mode - Opens file for writingcreates a new file (overwrites if file exists)
'a'Append mode - Opens file for appendingcreates 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.
  • Reading Text Files
    1. Use read() method to read the entire file
    2. Use readlines() method to read all lines in a list
    Writing Text Files
    1. Use write() method to write a string to a file
    2. Use writelines() method to write a list of strings to a file

Reading Text Files

    Approach 1:
    1. file_obj = open("sample.txt", "r") content = file_obj.read() print(content) file_obj.close()
    Approach 2 (Preferred):
    1. with open("sample.txt", "r") as file_obj:content = file_obj.read() # Try with readline() and readlines() print(content)

Writing Text Files

  • For rest, we will use context manager to handle file operations.
  • Example:
    1. with open("output.txt", "w") as file_obj:file_obj.write("Hello, World!\n")file_obj.write("How are you?")
    2. 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?

Reading CSV Files

  • Python provides csv module to read and write CSV files
  • Example:
    1. import csv with 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 values
    2. import csv with 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

Writing CSV Files

    Example:
    1. import csv data = [["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)
    2. import csv data = [{"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)

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 json module to read and write JSON files
  • JSON Example:
    1. {"name": "Rabindra", "age": 30}
    2. {"country": "Napal", "cities": ["Kathmandu", "Pokhara", "Lalitpur"]}
    3. {"name": "Ram", "age": 27, "is_student": false, "courses": ["Python", "JS"]}

Serialization and Deserialization

  • Serialization => Converting a Python object into a JSON string
  • Deserialization => Converting a JSON string back into a Python object
  • Serialization Example:
    1. import json data = {"name": "Rabindra", "age": 30} json_string = json.dumps(data) print(json_string) # Check data type of data and json string
    Deserialization Example:
    1. import json json_string = '{"name": "Rabindra", "age": 30}' data = json.loads(json_string) print(data["name"]) # Check datatype of json string and data

Reading and Writting JSON Files

    Reading Json File
    1. import json with open("data.json", "r") as file_obj:data = json.load(file_obj) print(data) # Python object (dict or list)
    Writing Json File
    1. import json data = {"name": "Python", "duration": 30} with open("output.json", "w") as file_obj:json.dump(data, file_obj)