October 31: File I/O

Learning Objectives

After today's class, you should be able to:

  • Create files, read and write to/from files
  • Explain sys.argv and what command-line arguments are
  • Summarize what you can do with the os and sys modules.

Reminders

  • PA 1 Poker Dice part B is due 11/1 and worth 70 points
    • submit two files: score_dice.py and test_score_dice.py
    • submit attribution statement

Inclass Activity

Continue Lecture on I/O

Command Line

In Thonny, go to Tools → Open system shell…

  • Also known as the "command line" or "terminal"
  • Take some time to learn a few commands

  • Important symbols

    • ~ (tilde) means home directory
    • . (dot) means current directory
    • .. (dot dot) means parent directory

Command line example

Copy into thonny (recall this homework?):

import random

heads = 0
tails = 0
times = 1000000

for _ in range(times):
    if random.random() < 0.5:
        heads += 1
    else:
        tails += 1

heads = round(heads / times * 100, 2)
tails = round(tails / times * 100, 2)

print(f"Head: {heads}%, Tail: {tails}%")
save as coin_toss.py in a directory for python programs

From the command line, use the python3 command to run a program.

$ python3 coin_toss.py

OR

From Thonny, press Ctrl + t or ^Ctrl+ T to "Run current script in terminal."

Program Arguments

Copy into Thonny and save as print_args.y:

import sys

def main():
    for i, arg in enumerate(sys.argv):
        print(f"argv[{i}] == '{arg}'")

if __name__ == "__main__":
    main()
  • From the View menu in Thonny, turn on the "Program Arguments" box, type in Go Dukes and run

OR

  • In the Thonny shell

>>> %Run print_args.py Go Dukes

OR

  • In the terminal,

$ python3 print_args Go Dukes

Walking the File System

  • os.walk() returns a three-tuple
"""Find all Python files in a given directory."""

import os
import sys

def main(path):

    # for each directory starting from path
    for root, dirs, files in os.walk(path):
        print()
        # self documenting instructions
        print(f"{root = }") 
        print(f"{dirs = }")
        print(f"{files = }")
        print()
        # for each Python file in current directory
        for filename in sorted(files):
            if filename.endswith(".py"):
                filepath = os.path.join(root, filename)
                print(filepath)

if __name__ == "__main__":
    if len(sys.argv) == 1:
        # no arguments; use current directory
        main(".")
    else:
        # use the "first" command-line argument
        main(sys.argv[1])
  • Modify this program so that it takes a second command-line argument that is the name of a particular file to search for. Print the full path to the file if it is found. Keep in mind that there could be multiple files with the same name. For example:
$  python3 search.py /home/simmonsj names.txt
/home/simmonsj/Downloads/149/Act11/src/names.txt
/home/simmonsj/courses/CS101/docs/grading/F22/names.txt

Your To-Do List

Due Wednesday November 1st at 11pm

  • Submit PA 1 Part B (70 points) through Canvas
  • Remember the attribution statement

Prepare for Quiz 4B

  • review material from Quiz 4A
  • review all material regarding while loops and import

By Thursday