reading-notes

Read & Write Files in Python

What Is a File?

a file is a contiguous set of bytes used to store data

Files are composed of three main parts:

1- Header: metadata about the contents of the file

2- Data: contents of the file as written by the creator or editor

3- End of file (EOF): special character that indicates the end of the file

File Paths

The file path is a string that represents the location of a file.

three major parts of paths:

1- Folder Path

2- File Name

3- Extension

/
│
├── path/
|   │
│   ├── to/
│   │   └── cats.gif
│   │
│   └── dog_breeds.txt
|
└── animals.csv

Line Endings

line endings should use the sequence of the Carriage Return (CR or \r) and the Line Feed (LF or \n) characters (CR+LF or \r\n).

Opening and Closing a File in Python

When you want to work with a file, the first thing to do is to open it.

file = open('dog_breeds.txt')

It’s important to remember that it’s your responsibility to close the file.

Text File Types

A text file is the most common file that you’ll encounter.

open('abc.txt')

open('abc.txt', 'r')

open('abc.txt', 'w')

Python Exceptions: An Introduction

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

Exceptions versus Syntax Errors

Syntax errors occur when the parser detects an incorrect statement.

>>> print( 0 / 0 ))
  File "<stdin>", line 1
    print( 0 / 0 ))
                  ^
SyntaxError: invalid syntax

Raising an Exception

We can use raise to throw an exception if a condition occurs.

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

The AssertionError Exception

We assert that a certain condition is met

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

The try and except Block: Handling Exceptions

The try and except block in Python is used to catch and handle exceptions.

def linux_interaction():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')