-
Notifications
You must be signed in to change notification settings - Fork 0
Chapter 10: Files and Exception
Jarlin Almanzar edited this page Nov 23, 2019
·
4 revisions
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)
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)
with open('/user/jarlin/files/numbers.txt') as file_object:
for line in file_object:
print(line)
print(contents)
with open('numbers.txt') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.strip())
'w' write mode
filename = 'program.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming")
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!")
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.
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)