Make me look good. Click on the cell below and press Ctrl+Enter.
from IPython.core.display import HTML
HTML(open('css/custom.css', 'r').read())
try
-except
blocksIn the same folder as this notebook, there is a file called demo.txt
.
The code below reads from demo.txt
, and stores its contents as a string in a variable called contents
.
# Read demo.txt and print its contents
with open("demo.txt") as file_object:
contents = file_object.read()
print(contents)
This is a text file example. We will use it to demonstrate how to work with text files in class. This is the last line in the file.
Line 2 opens demo.txt
and creates a file object called file_object
.
with
keyword closes the file once we no longer need access to it.Line 3 uses the .read()
method of a file object to read the contents of the file as a string.
You can also read a text file one line at a time.
Note. When Python reads from a text file, it interprets all text in the file as a string.
int()
or float()
.What if the file you wanted to read was not in the same folder as this notebook?
In this case, you would need to provide the path to the file.
You can either provide:
Note that the Windows operating system uses a backslash (\) when displaying file paths, while Unix-based systems use a forward slash (/). Python will allow you to use forward slashes in your code even on Windows. If you want to use backslashes, you will need to use \\
instead of \
in order to tell Python to interpret them correctly. For example, you would want to write a path like the following in Windows if you want to use backslashes:
C:\\path\\to\\file.txt
To write text to a file, you need to call open()
with a second argument telling Python that you want to write to the file.
The code below asks the user to enter some text to be stored in a file, and then writes it to the file write_example.txt
.
# Ask user for input
file_contents = input("Enter some text to be stored in a file: ")
# Write input to file
with open("write_example.txt", 'w') as file_object:
file_object.write(file_contents)
Enter some text to be stored in a file: I am trapped inside a computer.
open()
can one of several things, including:Character | Meaning |
---|---|
'r' |
read-only mode |
'w' |
write mode: first erase file if it exists |
'a' |
append mode: add to end of file if it exists |
There are a few others: here's the documentation.
If you omit the second argument, Python opens the file in read-only mode by default.
The open()
function will automatically create the file you're writing to if it doesn't already exist.
Be careful when using the write mode argument 'w'
!
'w'
mode to open the file, open()
will ERASE the contents of the file before returning the file object. 😱'a'
or append mode argument.The JavaScript Object Notation (JSON) format was originally developed for JavaScript.
It has become a common format used by many languages, including Python.
The json
module allows you to
json.dump()
to write a list to a JSON file:import json
# Here's a list that I want to write to a file
shopping_list = ['Carrots', 'Potatoes', 'Garlic', 'Chuck Roast', 'Beef Broth']
# Write the list to a file
with open('MyShoppingList.json', mode='w') as my_fileobj:
json.dump(shopping_list, my_fileobj)
MyShoppingList.json
and stores the contents in the variable sl
.# Read MyShoppingList.json and load into sl
with open('MyShoppingList.json', mode='r') as fileobj:
sl = json.load(fileobj)
sl
should be the same as shopping_list
. Did it work?# Print sl
print(sl)
# What is the type of sl?
print(type(sl))
['Carrots', 'Potatoes', 'Garlic', 'Chuck Roast', 'Beef Broth'] <class 'list'>
shopping_list
, are preserved in sl
as well as the structure of the data.sl
is a list just like the original data was in shopping_list
.An exception is a special object that Python creates when an error occurs.
When an error occurs, "an exception is raised".
A try
-except
block asks Python to do something, but it also tells Python what to do if an exception is raised.
Example.
A common error when working with files is that the provided file name is incorrect. The code below illustrates this error by attempting to load the file YourShoppingList.json
instead of the correct file MyShoppingList.json
.
filename = 'YourShoppingList.json'
# Read file
with open(filename, mode='r') as fileobj:
sl = json.load(fileobj)
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-7-97343694f92b> in <module>() 2 3 # Read file ----> 4 with open(filename, mode='r') as fileobj: 5 sl = json.load(fileobj) FileNotFoundError: [Errno 2] No such file or directory: 'YourShoppingList.json'
We can use a try
-except
block to handle this type of error and provide the user with a "friendly" error message if they enter a file name that doesn't exist.
filename = 'YourShoppingList.json'
# Try opening the file
# If the file doesn't exist, catch the exception
# and print a "friendly" error message.
try:
with open(filename, mode='r') as fileobj:
sl = json.load(fileobj)
except FileNotFoundError:
print(f"I'm sorry, the file {filename} does not exist!")
I'm sorry, the file YourShoppingList.json does not exist!
Example.
try
-except
blocks also give you the option to write multiple except blocks to handle different types of errors in different ways.
The code below asks the user to input two integers and attempts to divide them. If the user enters a value of 0 for the second number, the ZeroDivisionError
results, and the user is provided with an appropriate warning about division by zero.
If the user enters text-based values (like one or two) instead of numeric values or enters floating point numbers instead of integers, then the user gets a different error message.
Run the code below twice, and make a different error each time to see how Python handles it. Note that the final except
statement contains a "generic" error handling message that would be executed if any exception occurs other than a ZeroDivisionError
or a ValueError
.
# Ask user for input
print("Enter two integers and I'll attempt to divide them.")
first_number = input("First number: ")
second_number = input("Second number: ")
# Try dividing the two numbers
# Catch exceptions and print appropriate error messages
try:
answer = int(first_number) / int(second_number)
print(answer)
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Please enter integer, numeric values for the First and Second numbers.")
except:
print("Something else went wrong.")
Enter two integers and I'll attempt to divide them. First number: 99 Second number: 0 You can't divide by zero!
Problem 1 (PCC 10-1: Learning Python). Read pages 184-190 of PCC Chapter 10.
Open a blank file in your text editor and write a few lines summarizing what you’ve learned about Python so far. Start each line with the phrase "In Python you can..." Save the file as learning_python.txt
in the same directory as your exercises from this chapter. Write a program that reads the file and prints what you wrote three times:
with
block.# Read learning_python.txt, and print contents
# by reading in the entire file
with open("learning_python.txt") as file_object:
contents = file_object.read()
print(contents)
print("\n")
# Read learning_python.txt, and print contents
# by looping over each line.
# See page 187 pf PCC Chapter 10.
with open("learning_python.txt") as file_object:
for line in file_object:
print(line.rstrip())
print("\n")
# Read learning_python.txt, and print contents
# by storing the lines in a list and then working
# with them outside the with block.
# See page 188 pf PCC Chapter 10.
with open("learning_python.txt") as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
In Python you can write fun loops with for statements. In Python you can branch using if-elif-else statements. In Python you can do lots of cool math with the numpy package. In Python you can write fun loops with for statements. In Python you can branch using if-elif-else statements. In Python you can do lots of cool math with the numpy package. In Python you can write fun loops with for statements. In Python you can branch using if-elif-else statements. In Python you can do lots of cool math with the numpy package.
Problem 2 (PCC 10-2: Learning C). You can use the replace()
method to replace any word in a string with a different word. Here’s a quick example showing how to replace "dog" with "cat" in a sentence:
message = "I really like dogs."
# Replace "dog" with "cat" in message
# Store new string in message
message = message.replace("dog", "cat")
print(message)
I really like cats.
Read in each line from the file you just created, learning_python.txt
, and replace the word Python with the name of another language, such as C. Print each modified line to the screen.
# Read learning_python.txt, print its contents
# and replace "Python" with "C"
with open("learning_python.txt") as file_object:
contents = file_object.read()
print(contents.replace("Python","C"))
In C you can write fun loops with for statements. In C you can branch using if-elif-else statements. In C you can do lots of cool math with the numpy package.
Problem 3 (PCC 10-3: Guest). Write a program that prompts the user for their name. When they respond, write their name to a file called guest.txt
.
# Ask user for input
name = input("What is your name? ")
# Write user input to file
with open("guest.txt", 'w') as file_object:
file_object.write(name)
What is your name? Nelson
Problem 4. (PCC 10-4: Guest Book).
Write a while
loop that prompts users for their name. When they enter their name, print a greeting to the screen and add a line recording their visit in a file called guest_book.txt
. Make sure each entry appears on a new line in the file.
while True:
# Ask user for input
name = input("What is your name? (enter q to quit) ")
# If user inputs "q", then stop asking for input
# Otherwise, write user input to file
if name == 'q':
break
else:
with open("guest_book.txt", 'a') as file_object:
file_object.write(f"{name}\n")
# Note: appending to a file that doesn't exist just works like 'w':
# a new file is created.
What is your name? (enter q to quit) Jay What is your name? (enter q to quit) Will What is your name? (enter q to quit) Nelson What is your name? (enter q to quit) q
Problem 5 (PCC 10-6: Addition). One common problem when prompting for numerical input occurs when people provide text instead of numbers. When you try to convert the input to an int
, you’ll get a ValueError
. Write a program that prompts for two numbers. Add them together and print the result. Catch the ValueError
if either input value is not a number, and print a friendly error message. Test your program by entering two numbers and then by entering some text instead of a number.
# Ask user for input
num1 = input("Enter a number: ")
num2 = input("Enter a second number: ")
# Convert user input to integers and add
# If error occurs, print message.
try:
print(f"The sum of the two numbers is {int(num1) + int(num2)}.")
except ValueError:
print("You need to enter integers!")
Enter a number: 42 Enter a second number: this is not a number You need to enter integers!
Problem 6 (PCC 10-7: Addition Calculator). Wrap your code from Problem 5 in a while
loop so the user can continue entering numbers even if they make a mistake and enter text instead of a number.
# List of numbers to add
nums = []
while True:
# Ask for user input
num = input("Enter a number (enter d when done): ")
# If user inputs "d", then stop asking for input
# Otherwise, convert input to integer and add to
# list of numbers to add
# If conversion is not successful, print error message
if num == 'd':
break
else:
try:
nums.append(int(num))
except ValueError:
print("Numbers must be integers. Please continue.")
print(f"The sum of the numbers is {sum(nums)}.")
Enter a number (enter d when done): 1 Enter a number (enter d when done): 2 Enter a number (enter d when done): three Numbers must be integers. Please continue. Enter a number (enter d when done): 4 Enter a number (enter d when done): d The sum of the numbers is 7.
Problem 7 (PCC 10-8: Cats and Dogs).
Make two files, cats.txt
and dogs.txt
. Store at least three names of cats in the first file and three names of dogs in the second file. Write a program that tries to read these files and print the contents of the file to the screen. Wrap your code in a try-except
block to catch the FileNotFoundError
, and print a friendly message if a file is missing. Move one of the files to a different location on your system, and make sure the code in the except block executes properly.
def printcontents(file):
"""Print contents of file to screen"""
# Read file and print its contents
# If file doesn't exist, print error message
try:
with open(file) as file_object:
contents = file_object.read()
print(contents)
except FileNotFoundError:
print(f"Could not locate {file}.")
printcontents("cats.txt")
printcontents("dogs.txt")
printcontents("dogs1.txt")
Thomas Sammy Firepaw Lassie Red Spot Could not locate dogs1.txt.
Problem 8 (PCC 10-9: Silent Cats and Dogs). Read pages 200-201 of PCC Chapter 10..
Modify your except
block in Problem 7 to fail silently if either file is missing.
def printcontents(file):
"""Print contents of file to screen"""
# Read file and print its contents
# If file doesn't exist, just let it go
try:
with open(file) as file_object:
contents = file_object.read()
print(contents)
except FileNotFoundError:
pass
printcontents("cats.txt")
printcontents("dogs.txt")
printcontents("dogs1.txt")
Thomas Sammy Firepaw Lassie Red Spot
Problem 9. (PCC 10-10: Common Words). Visit Project Gutenberg and find a few texts you’d like to analyze.
Download the text files for these works, as follows. We're going to use the wget
module. This does not come with the standard distribution of Python so we'll install it.
Click on the Windows Start button, find Anaconda3 (64-bit), and then select Anaconda Prompt. This will bring up a terminal window.
In the window, type
pip install wget
Once you have wget
installed, you can run the following code, which downloads the text of Heart of Darkness by Joseph Conrad into a text file called HOD.txt
.
import wget
# Download the file at target_url
target_url = 'http://www.gutenberg.org/files/526/526.txt'
wget.download(target_url, 'HOD.txt')
'HOD.txt'
You can use the count()
method to find out how many times a word or phrase appears in a string. For example, the following code counts the number of times "row" appears in a string:
line = "Row, row, row your boat"
line.count('row')
2
# This is slightly different. Why?
line.lower().count('row')
3
Notice that converting the string to lowercase using lower()
catches all appearances of the word you’re looking for, regardless of how it’s formatted.
Write a program that reads the files you found at Project Gutenberg (pick at least one other book besides Heart of Darkness) and determines how many times the word "the" appears in each text.
Notes.
wget.download
adds (1)
, (2)
, etc. to the file name if the file you are downloading already exists in the current directory.
If you get a UnicodeDecodeError
, you may need to pass encoding='utf-8'
to open()
, like this:
with open(filename, encoding='utf-8') as file_object:
...
# Download the file at target_url
target_url = 'http://www.gutenberg.org/files/1342/1342-0.txt'
wget.download(target_url, 'PrideAndPrejudice.txt')
# Create dictionary mapping book titles to file names
book_list = {'Heart of Darkness' : 'HOD.txt',
'Pride and Prejudice' : 'PrideAndPrejudice.txt'}
# Iterate over the title-filename pairs
# Count the number of times "the" appears
for title, filename in book_list.items():
with open(filename, encoding='utf-8') as file_object:
contents = file_object.read()
print(f"The word 'the' appears {contents.lower().count('the')} times in {title}.")
The word 'the' appears 3402 times in Heart of Darkness. The word 'the' appears 7990 times in Pride and Prejudice.
Problem 10 (PCC 10-11: Favorite Number).
Write a function that prompts for the user’s favorite number. Use json.dump()
to store this number in a file.
Write a separate function that reads this value from the file and prints the message, I know your favorite number! It’s ____.
import json
def get_favorite_number(filename):
"""Ask user for favorite number and write it to a file"""
# Ask for user input
num = input("Enter your favorite number: ")
# Write JSON file with user input
with open(filename, 'w') as file_object:
json.dump(num, file_object)
def recover_favorite_number(filename):
"""Read favorite number from a file and print it"""
# Read JSON file containing favorite number
with open(filename, 'r') as file_object:
number = json.load(file_object)
print(f"I know your favorite number! It is {number}.")
# Write and read user's favorite number
# using functions defined above
filename = 'favorite_number.json'
get_favorite_number(filename)
recover_favorite_number(filename)
Enter your favorite number: 42 I know your favorite number! It is 42.
Problem 11 (PCC 10-12: Favorite Number Remembered). Combine the two functions from Problem 10 into one function. If the number is already stored, report the favorite number to the user. If not, prompt for the user’s favorite number and store it in a file. Call the function twice to see that it works.
import json
def favorite_number(filename):
"""
If the file doesn't exist, ask user for favorite number and write it to the file.
Otherwise, read the file and print the favorite number.
"""
# Try reading the JSON file and printing the favorite number.
# If the file is not found, ask for user input and
# write a JSON file with the user input.
try:
with open(filename, 'r') as file_object:
number = json.load(file_object)
print(f"I know your favorite number! It is {number}.")
except FileNotFoundError:
num = input("Enter your favorite number: ")
with open(filename, 'w') as file_object:
json.dump(num, file_object)
# Write and read user's favorite number using function defined above
filename = 'favorite_number_11.json'
favorite_number(filename)
favorite_number(filename)
Enter your favorite number: 11 I know your favorite number! It is 11.