Skip to content

Chapter 10: Files and Exception

Jarlin Almanzar edited this page Nov 23, 2019 · 4 revisions

Files and Exception

Reading from a file

open()
Open justs needs one argument, the name of the file you want to open.

with open('numbers.txt') as file_object:

read()
Once we open the file we need to read it,

with open('numbers.txt') as file_object:
    contents = file_object.read()

close()
You can close the file using close()

with open('numbers.txt') as file_object:
    contents = file_object.read()
print(contents)

File Paths

open() without a file path can only open a file if its stored in the current directory.

with open('/user/jarlin/files/numbers.txt') as file_object:
    contents = file_object.read()
print(contents)

Reading Line by Line

with open('/user/jarlin/files/numbers.txt') as file_object:
    for line in file_object:
        print(line)
print(contents)

Making a List of Lines from a File

with open('numbers.txt') as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.strip())

Writing to a File

'w' write mode

filename = 'program.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love programming")

Exceptions

Python uses special objects called exceptions to manage errors that arise during a program's execution.
If you don't handle the error, the program will halt and show a traceback.

Exceptions are handled by try-except blocks, which will make the program continue to run even with errors

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

Storing Data

A simple way to store data is using the json module, which allows you to dump simple Python data structures into a file and load the data from that file.

json dump() and load() method

import json

numbers = [0,1,1,2,3,5,8]
filename = 'numbers.json'

with open(filename, 'w') as f:
    json.dump(numbers, f)

with open(filename) as f:
    numbers = json.load(f)

print(numbers)
Clone this wiki locally