← All advanced lessons

Advanced Python / A05

Reading & Writing Files

File paths, reading, writing, appending, exceptions, JSON, and data persistence.

Advanced Python - 5. Reading and Writing Files

5. Reading and Writing Files

5.1 Reading From a File

5.1.1 Reading an Entire File

5.1.2 File Paths

5.1.3 Reading Line by Line

5.1.4 Making a List of Lines from a File

5.1.5 Working with a File’s Contents

5.2 Writing to a File

5.2.1 Writing to an Empty File

5.2.2 Writing Multiple Lines

5.2.3 Appending to a File

5.3 Exceptions (try / except)

5.3.1 try / except

5.3.2 Using Exceptions to Prevent Crashes

5.3.3 The “else” Block

5.3.4 Handling the FileNotFoundError Exception

5.3.5 Analyzing Text

5.3.6 Working with Multiple Files

Chapter 5 Assignments

A5.1 pi to 1,000,000 Digits

A5.2 Is Your Birthday Contained in PI?

A5.3 Replacing Words

A5.4 Take a Poll

A5.5 Checking input

A5.6 Addition

A5.7 Common Words

5. Reading and Writing Files

5.1 Reading From a File

5.1.1 Reading an Entire File

3.1415926535

8979323846

2643383279

with open('pi_digits.txt') as file_object:

contents = file_object.read()

print(contents)

3.1415926535

8979323846

2643383279

# There is a blank line here

with open('pi_digits.txt') as file_object:

contents = file_object.read()

print(contents.rstrip())

5.1.2 File Paths

5.1.3 Reading Line by Line

filename = 'pi_digits.txt'

with open(filename) as file_object:

for line in file_object:

print(line)

3.1415926535

8979323846

2643383279

filename = 'pi_digits.txt'

with open(filename) as file_object:

for line in file_object:

print(line.rstrip())

3.1415926535

8979323846

2643383279

5.1.4 Making a List of Lines from a File

filename = 'pi_digits.txt'

with open(filename) as file_object:

lines = file_object.readlines()

for line in lines:

print(line.rstrip())

5.1.5 Working with a File’s Contents

filename = 'pi_digits.txt'

with open(filename) as file_object:

lines = file_object.readlines()

pi_string = ''

for line in lines:

pi_string += line.rstrip()

print(pi_string)

print(len(pi_string))

3.1415926535 8979323846 2643383279

36

3.141592653589793238462643383279

32

5.2 Writing to a File

5.2.1 Writing to an Empty File

filename = ‘programming.txt’

with open(filename, ‘w’) as file_object:

file_object.write(“I love programming”)

I love programming

  • Python can only write strings to a text file. If you want to store numerical data in a text file, you will have to convert the data to string format first using the str() function.

5.2.2 Writing Multiple Lines

filename = ‘programming.txt’

with open(filename, ‘w’) as file_object:

file_object.write(“I love programming.”)

file_object.write(“I love it so much.”)

FILE CONTENTS:

I love programming.I love it so much.

filename = ‘programming.txt’

with open(filename, ‘w’) as file_object:

file_object.write(“I love programming.\n”)

file_object.write(“I love it so much.\n”)

FILE CONTENTS:

I love programming.

I love it so much.

5.2.3 Appending to a File

  • If you want to add content to a file instead of writing over existing content, you can open the file in append mode. Any lines you write to the file will be added at the end of the file. If the file doesn’t exist yet, Python will create an empty file for you.
  • Continuing the example above, we can add more to our love of programming file called programming.txt by writing this program. We use the ‘a’ argument to open the file for appending instead of writing over the existing file.

filename = ‘programming.txt’

with open(filename, ‘a’) as file_object:

file_object.write(“I also love going to school.\n”)

file_object.write(“I plan on passing all of my classes.\n”)

FILE CONTENTS:

I love programming.

I love it so much.

I also love going to school.

I plan on passing all of my classes.

5.3 Exceptions (try / except)

  • Python uses objects called exceptions to manage errors during a program's execution. Whenever an error occurs that makes Python unsure of what to do next, it creates an object exception.
  • If you don’t handle exceptions, the program will stop and show a traceback, which includes a report of the exception that was raised.

Example:

print(5/0) # You can’t divide something by zero, so we get an error

ERROR:

Traceback (most recent call last):

File “division.py”, line 1, in <module>

ZeroDivisionError: division by zero

  • The error ZeroDivisionError is an exception object. We can tell Python what to do when this happens

5.3.1 try / except

Image provided by RealPython

try:

print(5/0)

except: ZeroDivisionError:

print(“You can’t divide by zero!”)

You can’t divide by zero!

  • If more code followed the try-except block, the program would continue running. We will see an example of that in the next section.

5.3.2 Using Exceptions to Prevent Crashes

print("Give me two numbers, and I'll divide them.")

print("Enter 'q' to quit.")

while True:

first_number = input("\nFirst number: ")

if first_number == 'q':

break

second_number = input("Second number: ")

if second_number == 'q':

break

answer = int(first_number) / int(second_number)

print(answer)

OUTPUT:

Give me two numbers, and I’ll divide them.

Enter ‘q’ to quit.

First number: 5

Second number: 0

Traceback (most recent call last):

File “division.py”, line 9, in <module>

answer = int(first_number) / int(second_number)

ZeroDivisionError: division by zero

5.3.3 The “else” Block

print("Give me two numbers, and I'll divide them.")

print("Enter 'q' to quit.")

while True:

first_number = input("\nFirst number: ")

if first_number == 'q':

break

second_number = input("Second number: ")

try:

answer = int(first_number) / int(second_number)

except ZeroDivisionError:

print("You can't divide by 0!")

else:

print(answer)

  • If the try statement doesn’t succeed because of a division by zero error, we print a friendly message telling the user how to avoid this error. The program continues to run and the user never sees a traceback error.

OUTPUT:

Give me two numbers, and I’ll divide them.

Enter ‘q’ to quit.

First number: 5

Second number: 0

You can’t divide by 0!

First number: 5

Second number: 2

2.5

First number: q

5.3.4 Handling the FileNotFoundError Exception

Example: alice.py

filename = ‘alice.txt’

with open(filename, encoding = ‘utf-8’) as f_obj:

contents = f_obj.read()

Traceback (most recent call last):

File “alice.py”, line 3, in <module>

with open(filename, encoding=’utf-8’) as f_obj:

FileNotFoundError: [Errno 2] No such file or directory: ‘alice.txt’

filename = ‘alice.txt’

try:

with open(filename, encoding = ‘utf-8’) as f_obj:

contents = f_obj.read()

except FileNotFoundError:

msg = "Sorry, the file " + filename + " does not exist."

print(msg)

  • Because the code in the try block produces a FileNotFoundError, Python looks for an except block that matches that error. Python then runs the code in that block with the following message instead of a traceback:

Sorry, the file alice.txt does not exist.

5.3.5 Analyzing Text

Code:

title = “Alice in Wonderland”

print(title.split())

OUTPUT:

[‘Alice’, ‘in’, ‘Wonderland’]

filename = ‘alice.txt’

try:

with open(filename, encoding = ‘utf-8’) as f_obj:

contents = f_obj.read()

except FileNotFoundError:

msg = "Sorry, the file " + filename + " does not exist."

print(msg)

else:

# Count the approximate number of words in the file

words = contents.split()

num_words = len(words)

print("The file " + filename + " has about " +

str(num_words) + " words.")

OUTPUT:

The file alice.txt has about 29461 words.

  • There is some extra information in the file so the count is a little high, but it’s close.

5.3.6 Working with Multiple Files

def count_words(filename):

"""Count the approximate number of words in a file."""

try:

with open(filename, encoding = ‘utf-8’) as f_obj:

contents = f_obj.read()

except FileNotFoundError:

msg = "Sorry, the file " + filename + " does not exist."

print(msg)

else:

# Count the approximate number of words in the file

words = contents.split()

num_words = len(words)

print("The file " + filename + " has about " + str(num_words)

+ " words.")

filename = 'alice.txt'

count_words(filename)

def count_words(filename):

"""Count the approximate number of words in a file."""

try:

with open(filename, encoding = ‘utf-8’) as f_obj:

contents = f_obj.read()

except FileNotFoundError:

msg = "Sorry, the file " + filename + " does not exist."

print(msg)

else:

# Count the approximate number of words in the file

words = contents.split()

num_words = len(words)

print("The file " + filename + " has about " + str(num_words)

+ " words.")

filenames = ['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']

for filename in filenames:

count_words(filename)

OUTPUT:

The file alice.txt has about 29461 words.

Sorry, the file siddhartha.txt does not exist.

The file moby_dick.txt has about 215136 words.

The file little_women.txt has about 189079 words.

Failing Silently:

except FileNotFoundError:

pass

instead of:

except FileNotFoundError:

msg = "Sorry, the file " + filename + " does not exist."

print(msg)

we would end up with the following output:

The file alice.txt has about 29461 words.

The file moby_dick.txt has about 215136 words.

The file little_women.txt has about 189079 words.

(Maybe add a section on JSON for storing data)

Chapter 5 Assignments

A5.1 pi to 1,000,000 Digits

  • If we start with a text file that contains pi to 1,000,000 decimal places, we can create a string containing all of these digits. We don’t need to change our program from reading pi with 30 digits except to pass it a different file.
  • Print the first 50 decimal places of pi and the total number of digits in the string that you build
  • Use THIS FILE

OUTPUT:

3.141159265358979323846264338327950288419716939937510…

1000002

A5.2 Is Your Birthday Contained in PI?

if birthday in pi_string: # birthday in the form mmddyy

# pi_string holds the million digits of pi

# automatically checks if its in there

SAMPLE RUN:

Enter your birthdate, in the form mmddyy: 120372

Your birthday appears in the first million digits of pi!!

A5.3 Replacing Words

I am a student in Finkel’s class. Finkel teaches a lot of good stuff. Whenever I go

to Finkel’s class, I feel like I am expanding my mind, but I’m not sure Finkel would

agree.

A5.4 Take a Poll

A5.5 Checking input

A5.6 Addition

A5.7 Common Words

line = “Row, row, row your boat”

print(line.count(‘row’)) # prints 2

print(line.lower().count(‘row’)) # prints 3

lower() makes all of the words lower case.