reading-notes

FileIO & Exceptions

Reading and Writing Files in Python

One of the most common tasks that you can do with Python is reading and writing files.

What Is a File?

Opening and Closing a File in Python

reader = open('dog_breeds.txt')
try:
    # Further file processing goes here
finally:
    reader.close()
with open('dog_breeds.txt') as reader:
    # Further file processing goes here

Reading and Writing Opened Files

>>> with open('dog_breeds.txt', 'r') as reader:
>>>     # Read and print the entire file line by line
>>>     for line in reader:
>>>         print(line, end='')
with open('dog_breeds.txt', 'r') as reader:
    # 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)

Source: https://realpython.com/read-write-files-python/


Python Exceptions

In Python, an error can be a syntax error or an exception.

Exceptions versus Syntax Errors

Raising an Exception

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

The AssertionError Exception

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

The try and except Block: Handling Exceptions

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 FileNotFoundError as fnf_error:
    print(fnf_error)

The else Clause

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    print('Executing the else clause.')

Cleaning Up After Using finally

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.')

Source: https://realpython.com/python-exceptions/