Working With Files

open allows you to open a specific file in Python.

.seek = seeks the position within the file indicated by numbers [0] .read() = reads the file. Can only read through once. .readlines() = reads only first line of file. But if repeated, can read multiple lines. One after another. .close() = manually closes the file. Will not close the file without using this command.

Read, Write, Append

            `with open('test.txt') as my_file
                print(my_file.readlines())`

The above code is a standard way to read a file.

with open ('test.txt, mode='r') = Reads file by default if blank, but this syntax also works.

To indicate you want to write to a file, simply change the r to w. Which also creates a new file, if the one named does not exist.

r+ enables you to read & write.

a for appending the file. Writing at the end.

TO indicate the location of a file in a folder. Simply indicate the directory where the name of the file would go. Like this:

            `with open ('app/test.txt', mode='r')
                print(my_file.read())`

\ for windows systems / for UNIX based systems

An absolute path is the exact directory you are looking for the file.

A relative path is based on where the script will run relative to the present working directory.

./ will tell the computer to run the script from the current folder.

../ will try to run from the directory that is one folder above the pwd

Errors

            `try:
                with open('test.txt', mode='r') as my_file:
                print(my_file.read())
            except FileNotFoundError as err:
                print('file does not exist')
                raise err`

The syntax above is a common way to catch errors related to the file. raise err will bring up the computers error message, and adding the print statement will return your own custom message for the program.

You can also write the above code and have it catch an IOError which happens when the computer struggles to read the file properly.