Reading input from a file and showing some output to the Shell

You will need the following input file located in the SAME directory as your python code: alice.txt

# open the file for READING ("r")
with open("alice.txt", "r") as inputBook:
    numWords = 0
    
    # iterate through each line of the file
    for line in inputBook:
        
        # obtain a list of words from the text
        words = line.split()
        
        # accumulate the total number of words
        numWords += len(words)
    
    print("There are a total of {0} words".format(numWords))

Writing output to a file

When you run the following code, you can observe the output as a new file created called “output-numbers.txt” located in the SAME directory as your python code.

# open the file for WRITING ("w")
# - this creates the file if it didn't previously exist
# - this overwites the file if it already existed
with open("output-numbers.txt", "w") as outputFile:

    # iterate through numbers 0 to 24, inclusive
    for num in range(25):
        
        # include the number and newline character
        lineToWrite = "Number: {0} \n".format(num)
        
        # append string to the end of the file
        outputFile.write(lineToWrite)

Formatting a string

line1 = "{0} {1} {2} {3} {3} {3} {4}".format("here", "is", "a", "repeated", "example")
print(line1)

line2 = "{0} {1} cost ${2}".format(6, 'bananas', 1.42)
print(line2)