Today's lab focuses on formatting and file processing.
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 printfile.py from the book's website. Try running it. When it asks for a file, type in printfile.py. What does it print out?
Next, let's try it on the file allcaps.txt. Let's change the print line to
print(data.lower())What happens? Why?
To print to a file (instead of to the screen) is very easy:
Let's do that for the printfile.py program:
def main(): fname = input("Enter filename: ") infile = open(fname,"r") outfile = open("out.txt","w") data = infile.read() 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: print(line) main()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.