Recall: reading input from a file (locally)

This manner of reading input from a file requires that the input file is downloaded and saved locally on your computer in the SAME directory as your python code: alice.txt

# prints all lines from the file
with open("alice.txt", "r") as file:
    for line in file:
        print(line)

Reading input remotely from a website

This manner of reading input does NOT require you to download the file locally. Instead, it reads the input remotely. You must be connected to the internet in order to perform this operation, and the file must exist as named on the server specified.

It takes a URL (uniform resource locator), which is a unique address pointing to the file.

import urllib.request

url = urllib.request.urlopen("http://csweb.wooster.edu/hguarnera/cs100/code-examples/ch5/alice.txt")
lines = url.readlines() # returns a list of byte strings
for line in lines:
    #print( line )   # prints the line as a byte string: b'content'
    print( line.decode("utf-8") ) # convert the byte string to a standard string

List comprehensions

# instantiates a list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
myList = [x for x in range(10)]

# instantiates a list of even numbers: [0, 2, 4, 6, 8]
myList = [x for x in range(10) if x % 2 == 0]

# instantiates a list of large even numbers: [6, 8]
myList = [x for x in range(10) if x % 2 == 0 and x > 5]

# instantiates a list: [0, 10, 20, 30, 40]
myList = [x * 10 for x in range(5)]