Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Reading

(3h)

Reading PDF.

Concepts:

  • 6.1 Introduction to File I/O

    • Motivation: read from the file at a later time

    • Opening, processing, closing a file

    • Types of files

    • File access methods, sequential, direct. We will use sequential

    • Opening a file f = open(filename, mode)

      • read, write, append

    • Specifying the location of a file

      • Use r in Windows r'C:\Users\...

    • Writing data to a file

      • f.write(string)

      • f.close()

    • Reading data from a file

      • contents = f.read()

    • Concatenating a newline to a string

      • "string" + "\n"

    • Reading a string and stripping a newline from it

      • string.rstrip('\n')

    • Appending data to an existing file

      • f = open("file.txt", "a")

    • Writing and reading numeric data

      • str(number)

  • 6.2 Using loops to process files

    • Reading a file with a loop and detecting the end of the file

      • f.readline(); while line != ""; f.readline()

    • MORE CONVENIENT using for

      • for line in f:

    • Spotlight: Working with files

  • 6.3 Using the with statement to open files

    • a resource typically goes through open, work, close.

    • with open("filename", mode) as f:

    • multiple: with open() as f1, open() as f2:

  • 6.4 Processing records

    • for each data, use a new line

    • Examples: Adding and displaying records, searching for a record, modifying records (creating a temp file and deleting it), deleting records

  • 6.5 Exceptions

    • exceptions make the program halt.

    • try except allows graceful handling

    • try:
        statements that can make the program halt
      except Exception:
        graceful handling
    • look before you leap (LBYL) vs easier to ask forgiveness than permission (EAFP)

    • Examples: dividing by zero, wrong input (int("hello"))

    • Multiple exceptions: except, except ...

    • Displaying an exception’s default error message: except Ex as err

    • else block: only if no exceptions have occurred

    • finally

    • What if an exception is not handled?