Lecture 17 — Data from Files and Web Pages

Overview

  • Review of string operations

  • Files on your computer

    • Opening and reading files

    • Closing

    • Writing files

  • Accessing files across the web

  • Parsing basics

  • String Operations

Opening and Reading Files

  • Given the name of a file as a string, we can open it to read:

    f = open('abc.txt')
    

    This is the same as:

    f = open('abc.txt', 'r')
    
    • Variable f now “points” to the first line of file abc.txt.

    • The 'r' tells Python we will be reading from this file — this is the default.

Reading the Contents of a File

  • The most common way to read a file is illustrated in the following example that reads each line from a file and prints it on the screen:

    f = open('abc.txt')
    for line in f:
        print(line)
    

    (Of course you can replace the call to print() with any other processing code since each line is just a string!)

  • You can combine the above steps into a single for loop:

    for line in open('abc.txt'):
        print(line)
    

Closing and Reopening Files

  • The code below opens, reads, closes, and reopens a file:

    f = open('abc.txt')
    
    # Insert whatever code is need to read from the file
    # and use its contents ...
    
    f.close()
    f = open('abc.txt')
    
  • f now points again to the beginning of the file.

  • This can be used to read the same file multiple times.