[go: up one dir, main page]

0% found this document useful (0 votes)
49 views2 pages

Beginners Python Cheat Sheet PCC Files Exceptions BW

Uploaded by

amkslade101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views2 pages

Beginners Python Cheat Sheet PCC Files Exceptions BW

Uploaded by

amkslade101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Beginner's Python

Writing to a file Path objects (cont.)


The write_text() method can be used to write text to a Build a path
file. Be careful, this will write over the current file if it already

Cheat Sheet -
base_path = Path("/Users/eric/text_files")
exists. To append to a file, read the contents first and then
file_path = base_path / "alice.txt"
rewrite the entire file.
Writing to a file Check if a file exists

Files and Exceptions from pathlib import Path >>> path = Path("text_files/alice.txt")
>>> path.exists()
True
path = Path("programming.txt")
Why work with files? Why use exceptions? msg = "I love programming!"
Get filetype
Your programs can read information in from files, and path.write_text(msg) >>> path.suffix
they can write data to files. Reading from files allows '.txt'
Writing multiple lines to a file
you to work with a wide variety of information; writing
to files allows users to pick up where they left off the from pathlib import Path The try-except block
next time they run your program. You can write text to When you think an error may occur, you can write a try-
path = Path("programming.txt") except block to handle the exception that might be raised.
files, and you can store Python structures such as lists
in data files as well. The try block tells Python to try running some code, and the
msg = "I love programming!" except block tells Python what to do if the code results in a
Exceptions are special objects that help your msg += "\nI love making games."
particular kind of error.
programs respond to errors in appropriate ways. path.write_text(msg)
For example if your program tries to open a file that Handling the ZeroDivisionError exception
Appending to a file
doesn’t exist, you can use exceptions to display an try:
from pathlib import Path print(5/0)
informative error message instead of having the
program crash. except ZeroDivisionError:
path = Path("programming.txt") print("You can't divide by zero!")
contents = path.read_text()
Reading from a file Handling the FileNotFoundError exception
To read from a file your program needs to specify the contents += "\nI love programming!"
from pathlib import Path
path to the file, and then read the contents of the file. The contents += "\nI love making games."
read_text() method returns a string containing the entire path.write_text(contents)
path = Path("siddhartha.txt")
contents of the file. try:
Reading an entire file at once Path objects contents = path.read_text()
The pathlib module makes it easier to work with files in except FileNotFoundError:
from pathlib import Path msg = f"Can’t find file: {path.name}."
Python. A Path object represents a file or directory, and lets
you carry out common directory and file operations. print(msg)
path = Path('siddhartha.txt')
contents = path.read_text() With a relative path, Python usually looks for a location
relative to the .py file that's running. Absolute paths are Knowing which exception to handle
print(contents) relative to your system's root folder ("/"). It can be hard to know what kind of exception to handle
Windows uses backslashes when displaying file paths, but when writing code. Try writing your code without a try block,
Working with a file's lines you should use forward slashes in your Python code. and make it generate an error. The traceback will tell you
It's often useful to work with individual lines from a file. Once the
Relative path what kind of exception your program needs to handle. It's a
contents of a file have been read, you can get the lines using the
splitlines() method.
good idea to skim through the exceptions listed at
path = Path("text_files/alice.txt") docs.python.org/3/library/exceptions.html.
from pathlib import Path Absolute path
path = Path('siddhartha.txt')
contents = path.read_text()
path = Path("/Users/eric/text_files/alice.txt")
Python Crash Course
Get just the filename from a path A Hands-on, Project-Based
lines = contents.splitlines()
>>> path = Path("text_files/alice.txt") Introduction to Programming
for line in lines: >>> path.name ehmatthes.github.io/pcc_3e
print(line) 'alice.txt'
The else block Failing silently Storing data with json
The try block should only contain code that may cause Sometimes you want your program to just continue running The json module allows you to dump simple Python data
an error. Any code that depends on the try block running when it encounters an error, without reporting the error to the structures into a file, and load the data from that file the next
successfully should be placed in the else block. user. Using the pass statement in an except block allows time the program runs. The JSON data format is not specific
you to do this. to Python, so you can share this kind of data with people
Using an else block
who work in other languages as well.
print("Enter two numbers. I'll divide them.")
Using the pass statement in an except block
Knowing how to manage exceptions is important when
from pathlib import Path working with stored data. You'll usually want to make sure
x = input("First number: ") the data you're trying to load exists before working with it.
y = input("Second number: ") f_names = ['alice.txt', 'siddhartha.txt',
'moby_dick.txt', 'little_women.txt'] Using json.dumps() to store data
try: from pathlib import Path
result = int(x) / int(y) for f_name in f_names: import json
except ZeroDivisionError: # Report the length of each file found.
print("You can't divide by zero!") path = Path(f_name) numbers = [2, 3, 5, 7, 11, 13]
else: try:
print(result) contents = path.read_text() path = Path("numbers.json")
except FileNotFoundError: contents = json.dumps(numbers)
Preventing crashes caused by user input pass path.write_text(contents)
Without the except block in the following example, the program else:
would crash if the user tries to divide by zero. As written, it will lines = contents.splitlines() Using json.loads() to read data
handle the error gracefully and keep running. msg = f"{f_name} has {len(lines)}" from pathlib import Path
"""A simple calculator for division only.""" msg += " lines." import json
print(msg)
print("Enter two numbers. I'll divide them.") path = Path("numbers.json")
print("Enter 'q' to quit.") Avoid bare except blocks contents = path.read_text()
Exception handling code should catch specific exceptions numbers = json.loads(contents)
while True: that you expect to happen during your program's execution.
x = input("\nFirst number: ") print(numbers)
A bare except block will catch all exceptions, including
if x == 'q':
keyboard interrupts and system exits you might need when Making sure the stored data exists
break
forcing a program to close.
If you want to use a try block and you're not sure from pathlib import Path
y = input("Second number: ") import json
if y == 'q': which exception to catch, use Exception. It will catch
break most exceptions, but still allow you to interrupt programs
path = Path("numbers.json")
intentionally.
try: Don't use bare except blocks try:
result = int(x) / int(y) contents = path.read_text()
except ZeroDivisionError: try:
except FileNotFoundError:
print("You can't divide by zero!") # Do something
msg = f"Can't find file: {path}"
else: except:
print(msg)
print(result) pass
else:
Use Exception instead numbers = json.loads(contents)
Deciding which errors to report print(numbers)
try:
Well-written, properly tested code is not very prone to # Do something
internal errors such as syntax or logical errors. But every except Exception: Practice with exceptions
time your program depends on something external such as pass Take a program you've already written that prompts for user
user input or the existence of a file, there's a possibility of an input, and add some error-handling code to the program.
exception being raised. Printing the exception Run your program with appropriate and inappropriate data,
It's up to you how to communicate errors to your try: and make sure it handles each situation correctly.
users. Sometimes users need to know if a file is missing; # Do something
sometimes it's better to handle the error silently. A little except Exception as e:
experience will help you know how much to report. print(e, type(e)) Weekly posts about all things Python
mostlypython.substack.com

You might also like