reading-notes

FileIO & Exceptions

Files

Source: Read & Write Files in Python

FIles consist of:

  1. Header - metadata (e.g. name, type)
  2. Data - content
  3. End of File - character at end

Line Endings

\r\n for windows

Pug\r\n
Jack Russell Terrier\r\n

\r for unix or mac

Pug\r
\n
Jack Russell Terrier\r
\n

Character Encodings

Opening / Closing a File

Open

file = open('dog_breeds.txt')

Close

try:
    # Further file processing goes here
finally:
    reader.close()

Using with will close automatically

with open('dog_breeds.txt', 'r') as reader:
    # Further file processing goes here

Options

File Types

Reading and Writing Open Files

Iterating Over File Lines

readline()

 with open('dog_breeds.txt', 'r') as reader:
     # Read and print the entire file line by line
     line = reader.readline()
     while line != '':  # The EOF char is an empty string
         print(line, end='')
         line = reader.readline()

readlines()

 with open('dog_breeds.txt', 'r') as reader:
     for line in reader.readlines():
         print(line, end='')

file

 with open('dog_breeds.txt', 'r') as reader:
     # Read and print the entire file line by line
     for line in reader:
         print(line, end='')

Writing files

    # Note: readlines doesn't trim the line endings
    dog_breeds = reader.readlines()

with open('dog_breeds_reversed.txt', 'w') as writer:
    # Alternatively you could use
    # writer.writelines(reversed(dog_breeds))

    # Write the dog breeds to the file in reversed order
    for breed in reversed(dog_breeds):
        writer.write(breed)

Appending

with open('dog_breeds.txt', 'a') as a_writer:
    a_writer.write('\nBeagle')

Working with two files

d_path = 'dog_breeds.txt'
d_r_path = 'dog_breeds_reversed.txt'
with open(d_path, 'r') as reader, open(d_r_path, 'w') as writer:
    dog_breeds = reader.readlines()
    writer.writelines(reversed(dog_breeds))

Resources

Reading and Writing CSV Files in Python Working With JSON Data in Python

Exceptions

Source: Python Exceptions: An Introduction

vs. Syntax Errors

Raising an exceptions

Throw an exceptions (standard or custom) if certain condition occurs:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))

Results in:

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10

AssertionError

Assert that a specfic condition is met, instead of waiting for failure:

import sys
assert ('linux' in sys.platform), "This code runs on Linux only."

Results in:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.

Try and except

Try some code, and catch an exception if it occurs

try:
    linux_interaction()
except AssertionError as error:
    print(error)
    print('The linux_interaction() function was not executed')
try:
    with open('file.log') as file:
        read_data = file.read()
except:
    print('Could not open file.log')

Else

Runs in absense of error:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    print('Executing the else clause.')
try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)

Finally

Use finally to clean up after code execution

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print('Cleaning up, irrespective of any exceptions.')

Summary