Today's lab focuses on formatting and file processing.

Working With Files

Python has many built-in functions for working with strings and files (string methods). In this lab, we will manipulate files using various string methods.

Let's start with the program from the book's website. Try running it. When it asks for a file, type in What does it print out?

Next, let's try it on the file allcaps.txt. Let's change the print line to

What happens? Why?

To print to a file (instead of to the screen) is very easy:

Let's do that for the program:

def main():
    fname = input("Enter filename: ")
    infile = open(fname,"r")
    outfile = open("out.txt","w")
    data =
    print(data, file=outfile)
Run the program. Where did it send the output? Modify this program so that all the output is in lowercase and test it on the text file above.

In python, there's often many different ways to write the same program. Let's write a program that prints the lines of a file using a for loop:

def main():
    print("This program prints a file.")

    # get the input file name
    infileName = input("Please enter name of input file: ")

    # open the files:
    infile = open(infileName, "r")

    # read each line of the input file and print it to outfile
    for line in infile:

What happens when you run this program? Why is it doublespacing the output? When you read a line from a file, it ends with an enter or `newline' character (often represented as `\n'. We can solve this in several different ways. One way to keep the last character of a line from being printed, we can use the slice operator to truncate the string:
	print(line[:-1], file = outfile)
The slice, line[:-1] says that you would like the string that consists of all the characters in line up to but not including the last character (since the -1 index always refers to the last character of a string, no matter how long the string is).

Modify this second program to print out the file all lowercase and singlespaced, and test it.