Files

Reading Files

Up to now the only way we've used large portions of data in our code is to put it directly into the code.

Let's learn how to read data from files.

Let's read from the file declaration-of-independence.txt.

We're going to start by using a shortcut, via Python's pathlib module.

First we need to import the Path type from Python's pathlib module:

>>> from pathlib import Path

Then we can make a new path object by supplying a filename:

>>> declaration_path = Path("declaration-of-independence.txt")

Then we can call the read_text method on that Path object to read the whole file into a string:

>>> declaration = declaration_path.read_text()

Writing Files

We can write to a file in a similar fashion.

Let's write Yay PyCon to a new file, called pycon2023.txt:

>>> pycon_path = Path("pycon2023.txt")
>>> pycon_path.write_text("Yay PyCon")

Now let's do some exercises!

File Exercises

Jot

Here's a program that prompts a user for input and prints out the current date:

from datetime import date
user_message = input("> ")
print(str(date.today()))

Create a jot.py program that adds a new line to the end of a jot.txt file, with the current date shown just before it.

For example (the ``> `` is printed by the program below and the text after it was inputted by the user):

$ python3 jot.py
> I'm currently learning Python.

If jot.txt was empty, that would make it:

2023-04-18: I'm currently learning Python.

If we run it again and type a new message:

$ python3 jot.py
> I'm at PyCon now.

Replace

Make a replace.py program which accepts a filename, a source phrase, and a replacement phrase and which replaces the source phrase with the replacement one within the file.

For example give a welcome.txt file like this:

Welcome to PyCon US 2022!

You may want to attend the Necomer's Orientation tomorrow.

Instead of using the hashtag #PyCon or #PyCon2022, you may want to use #PyConUS.

If we run replace.py, it should prompt the user to enter a filename and a replacement phrase like this:

$ python3 replace.py
File: welcome.txt
Phrase: 2022
Replacement: 2023

The user typed welcome.txt, 2022, and 2023.

The file welcome.txt should now contain:

Welcome to PyCon US 2023!

You may want to attend the Necomer's Orientation tomorrow.

Instead of using the hashtag #PyCon or #PyCon2023, you may want to use #PyConUS.

Hint

You may want to use the string replace method.

Count

Make a count.py program like this:

from argparse import ArgumentParser
from pathlib import Path

parser = ArgumentParser()
parser.add_argument("filename")
parser.add_argument("phrase")
args = parser.parse_args()

filename = args.filename
phrase = args.phrase

count = 0  # TODO count how many times the phrase appears in the file

print(repr(phrase), "appears in", repr(filename), count, "times")

Change this program to count how many times the given phrase appears in the given file.

You should be able to call the program like this:

$ python3 count.py welcome.txt pycon
'pycon' appears in 'welcome.txt' 4 times

Note that the phrase counting should be case-insensitive.

Hint

You may want to use the string count method.