Beginners Python Cheat Sheet PCC Files Exceptions

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Beginner's Python

Reading from a file (cont.) File paths (cont.)


Storing the lines in a list Opening a file using an absolute path

Cheat Sheet – filename = 'siddhartha.txt' f_path = "/home/ehmatthes/books/alice.txt"

Files and Exceptions


with open(filename) as f_obj: with open(f_path) as f:
lines = f_obj.readlines() lines = f.readlines()

for line in lines: Opening a file on Windows


Windows will sometimes interpret forward slashes incorrectly. If
print(line.rstrip())
you run into this, use backslashes in your file paths.
What are files? What are exceptions? f_path = "C:\Users\ehmatthes\books\alice.txt"
Writing to a file
Your programs can read information in from files, and Passing the 'w' argument to open() tells Python you want
they can write data to files. Reading from files allows with open(f_path) as f:
to write to the file. Be careful; this will erase the contents of lines = f.readlines()
you to work with a wide variety of information; writing the file if it already exists. Passing the 'a' argument tells
to files allows users to pick up where they left off the Python you want to append to the end of an existing file.
next time they run your program. You can write text to The try-except block
files, and you can store Python structures such as Writing to an empty file When you think an error may occur, you can write a try-
lists in data files. filename = 'programming.txt' except block to handle the exception that might be raised.
The try block tells Python to try running some code, and
the except block tells Python what to do if the code results
Exceptions are special objects that help your with open(filename, 'w') as f:
f.write("I love programming!") in a particular kind of error.
programs respond to errors in appropriate ways. For
example if your program tries to open a file that Writing multiple lines to an empty file Handling the ZeroDivisionError exception
doesn’t exist, you can use exceptions to display an
filename = 'programming.txt' try:
informative error message instead of having the print(5/0)
program crash. except ZeroDivisionError:
with open(filename, 'w') as f:
f.write("I love programming!\n") print("You can't divide by zero!")
Reading from a file f.write("I love creating new games.\n") Handling the FileNotFoundError exception
To read from a file your program needs to open the file and
Appending to a file f_name = 'siddhartha.txt'
then read the contents of the file. You can read the entire
contents of the file at once, or read the file line by line. The filename = 'programming.txt'
with statement makes sure the file is closed properly when try:
the program has finished accessing the file. with open(filename, 'a') as f: with open(f_name) as f:
f.write("I also love working with data.\n") lines = f.readlines()
Reading an entire file at once f.write("I love making apps as well.\n") except FileNotFoundError:
filename = 'siddhartha.txt' msg = f"Can’t find file: {f_name}."
print(msg)
File paths
with open(filename) as f_obj:
contents = f_obj.read() When Python runs the open() function, it looks for the file Knowing which exception to handle
in the same directory where the program that's being
executed is stored. You can open a file from a subfolder It can be hard to know what kind of exception to handle
print(contents) when writing code. Try writing your code without a try
using a relative path. You can also use an absolute path to
Reading line by line open any file on your system. block, and make it generate an error. The traceback will tell
Each line that's read from the file has a newline character at the you what kind of exception your program needs to handle.
end of the line, and the print function adds its own newline Opening a file from a subfolder
character. The rstrip() method gets rid of the extra blank lines
this would result in when printing to the terminal.
f_path = "text_files/alice.txt"
Python Crash Course
filename = 'siddhartha.txt' with open(f_path) as f: A Hands-On, Project-Based
lines = f.readlines() Introduction to Programming
with open(filename) as f_obj:
for line in f_obj: for line in lines:
print(line.rstrip()) print(line.rstrip()) nostarch.com/pythoncrashcourse2e
The else block Failing silently Storing data with json
The try block should only contain code that may cause an Sometimes you want your program to just continue running The json module allows you to dump simple Python data
error. Any code that depends on the try block running when it encounters an error, without reporting the error to structures into a file, and load the data from that file the
successfully should be placed in the else block. the user. Using the pass statement in an else block allows next time the program runs. The JSON data format is not
you to do this. specific to Python, so you can share this kind of data with
Using an else block people who work in other languages as well.
Using the pass statement in an else block
print("Enter two numbers. I'll divide them.")
f_names = ['alice.txt', 'siddhartha.txt', Knowing how to manage exceptions is important when
x = input("First number: ") 'moby_dick.txt', 'little_women.txt'] working with stored data. You'll usually want to make sure
y = input("Second number: ") the data you're trying to load exists before working with it.
for f_name in f_names: Using json.dump() to store data
try: # Report the length of each file found.
result = int(x) / int(y) try: """Store some numbers."""
except ZeroDivisionError: with open(f_name) as f:
print("You can't divide by zero!") lines = f.readlines() import json
else: except FileNotFoundError:
print(result) # Just move on to the next file. numbers = [2, 3, 5, 7, 11, 13]
pass
Preventing crashes from user input else: filename = 'numbers.json'
Without the except block in the following example, the program with open(filename, 'w') as f:
num_lines = len(lines)
would crash if the user tries to divide by zero. As written, it will
msg = f"{f_name} has {num_lines}" json.dump(numbers, f)
handle the error gracefully and keep running.
msg += " lines."
"""A simple calculator for division only.""" print(msg)
Using json.load() to read data
"""Load some previously stored numbers."""
print("Enter two numbers. I'll divide them.")
print("Enter 'q' to quit.")
Avoid bare except blocks
import json
Exception-handling code should catch specific exceptions
while True: that you expect to happen during your program's execution.
filename = 'numbers.json'
x = input("\nFirst number: ") A bare except block will catch all exceptions, including
with open(filename) as f:
if x == 'q': keyboard interrupts and system exits you might need when
numbers = json.load(f)
break forcing a program to close.
y = input("Second number: ") print(numbers)
if y == 'q': If you want to use a try block and you're not sure which
break exception to catch, use Exception. It will catch most Making sure the stored data exists
exceptions, but still allow you to interrupt programs
intentionally. import json
try:
result = int(x) / int(y) Don’t use bare except blocks f_name = 'numbers.json'
except ZeroDivisionError:
print("You can't divide by zero!") try:
try:
else: # Do something
with open(f_name) as f:
print(result) except:
numbers = json.load(f)
pass
except FileNotFoundError:
Deciding which errors to report Use Exception instead msg = f"Can’t find file: {f_name}."
Well-written, properly tested code is not very prone to print(msg)
try: else:
internal errors such as syntax or logical errors. But every
# Do something print(numbers)
time your program depends on something external such as
except Exception:
user input or the existence of a file, there's a possibility of
pass
an exception being raised. Practice with exceptions
Printing the exception Take a program you've already written that prompts for user
It's up to you how to communicate errors to your users. input, and add some error-handling code to the program.
Sometimes users need to know if a file is missing; try:
sometimes it's better to handle the error silently. A little # Do something
experience will help you know how much to report. except Exception as e: More cheat sheets available at
print(e, type(e)) ehmatthes.github.io/pcc_2e/

You might also like