Skip to content

File I/O

File I/O

  • Python has a built in function that allows us to open and write two files.

File I/O (Input/Output) allows us to read data from external files and write data back to them.


Opening and Reading Files

my_file = open('test.txt', 'r')

print(my_file.read())       # reads the whole file

my_file.seek(0)             # move cursor back to start
print(my_file.read())       # reads nothing because the cursor is at the end of the file

print(my_file.readline())   # reads the first line of the file
print(my_file.readlines())  # reads the whole file and returns a list of lines

my_file.close()             # always close files after use

Using with (Context Manager)

Always use with open(...) to ensure files are closed properly.

with open("file.txt", mode='r') as my_file:
    print(my_file.readlines())  

Automatically closes the file after the block of code is executed.

Writing to Files

r+ → read and write (overwrites content).

with open("test.txt", mode='r+') as my_file: 
    text = my_file.write(':)')                 
    print(text)

r+ allows us to read and write to the file. Writes to the file,overwrites the existing content.

w → write (creates new file or overwrites existing).

with open("test.txt", mode='w') as my_file:  
    my_file.write('I am writing to the file\n')  

w allows us to write to the file. Overwrites the existing content, \n adds a new line.

a → append (adds to end without overwriting).

with open("test.txt", mode='a') as my_file:  
    my_file.write('I am appending to the file\n')  

Use 'a' for appending to the file, it adds to the end of the file without overwriting the existing content.

Creating New Files

with open("new_file.txt", mode='w') as my_file: 
    my_file.write('I am sad\n')

Creates a new file if it doesn't exist, and writes to it.

Relative Paths

with open("./app/file.txt", mode='r+') as my_file:  # (relative path)to specify the path of the file
    print(my_file.write('I am sad again\n'))
  • ./ → current directory
  • ../ → parent directory/go back one directory
  • / → root directory

Error Handling in File I/O

Use try / except blocks to handle errors like FileNotFoundError or IOError.

try:
    with open("file.txt", mode='r+') as my_file:
        print(my_file.write('something'))
except FileNotFoundError as err:
    print("File not found")
    raise err
except IOError as err: 
    print("IO error")
    raise err

IO error is a more general error that can occur when working with files.

Pathlib Module pathlib provides a modern way to work with file paths across different operating systems (Windows, Mac, Linux) to manipulate file paths.

Binary File Handling

Binary files store data in raw byte format (e.g., images, audio, executables). - Unlike text files, they are not human-readable but can be processed efficiently. - Useful for handling images, audio, executables, or any non-text data.

Opening Binary Files

Use rb, wb, and ab modes when working with binary files:

rb → read binary wb → write binary (overwrites existing file or creates new) ab → append binary

  • Reading a binary file
with open("image.png", "rb") as file:
    data = file.read()
    print(type(data))   # <class 'bytes'>
  • Writing Binary Files
with open("output.bin", "wb") as file:
    file.write(b"Hello Binary World")
  • Copying Binary Files
with open("image.png", "rb") as src:
    with open("copy.png", "wb") as dest:
        dest.write(src.read())
  • Appending to Binary Files
with open("data.bin", "ab") as file:
    file.write(b"\x00\xFF")   # append raw bytes

Error Handling in Binary

Always handle exceptions when working with binary files:

try:
    with open("missing.bin", "rb") as file:
        data = file.read()
except FileNotFoundError:
    print("File not found")
except IOError:
    print("I/O error occurred")

JSON File Handling

JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging structured data.
Python provides the built-in json module to work with JSON files.


Reading JSON Files

Use json.load() to read JSON data from a file.

import json

with open("data.json", "r") as file:
    data = json.load(file)

print(data)          # Output: Python dictionary
print(data["name"])  # Access values by key

Writing JSON Files

Use json.dump() to write Python objects into a JSON file.

import json

person = {
    "name": "Marwa",
    "skills": ["Python", "Data Analysis"]
}

# Writing JSON to a file
with open("data.json", "w") as file:
    json.dump(person, file, indent=4)  # indent=4 makes it readable

Converting Between JSON Strings and Python Objects

  • json.loads() → parse JSON string into Python object.
  • json.dumps() → convert Python object into JSON string.
json_string = '{"name": "Marwa"}'
data = json.loads(json_string)
print(data["name"])   # Output: Marwa

python_obj = {"city": "Berlin", "country": "Germany"}
json_str = json.dumps(python_obj)
print(json_str)       # Output: {"city": "Berlin", "country": "Germany"}

Error Handling

Always handle exceptions when working with JSON:

import json

try:
    with open("data.json", "r") as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found")
except json.JSONDecodeError:
    print("Invalid JSON format")