Lab 5 Formatting and Files
Task 1, Formatting Text
Write a program that does each of the following. (Test one addition at a time.)
- Prompt the user for an integer:
Print out a sentence stating the square of the number, using a format string. - Prompt the user for two numbers.
Print
out a sentence listing both number and their quotient, using one format
string. Show three decimal places for each number.
Task 2, Reading Text Files:
- Open a new file in Idle, write in a few lines of text, and save it as "data.txt".
- Open a new file in Idle and save it as fhandler1.py
- Put these lines in fhandler1.py
fin = open('data.txt')
contents = fin.read()
print contents
fin.close()
- Save and execute the file. What type of variable is contents?
- Change the line contents = fin.read() to
contents = fin.readlines()
- Save and run fhandler1.py more time.
What type of variable is
contents?
What do you notice at the end of each string?
- Change the line
print contents
to
for line in contents:
print line
- Save and run.
- Even simpler, and useful for an enormous file you do not want to hold all at once:
fin = open('data.txt')
for line in fin:
print line
fin.close()
- Save and run fhandler1.py. What can you do to get rid of the extra newlines? Try it.
- Modify the code to print each line preceded by a line number
taking up three spaces, a colon, and two spaces, so the first line
would be prefaced by
" 1: ", and the 123rd line by "123: "
Task 3 Writing Text Files
To write to a file is simpler. Basically, one uses the following to open a file for writing
fout = open( 'writeMe.txt', 'w' )
And whenever you have a string to write <string> you use
fout.write( <string> )
Remember that <string> must end with ‘\n’ if you want an end of line. And you MUST finish with
fout.close() when you are completely done writing to the file!
Now write a program that will copy the data file from Task 1 to a new file called “backup.txt”
Open the backup file and check that you are correct.
Task 4, A Program with Text Files
Write a program to read one file, and copy it to another file with
line numbers added at the beginning of each line, in the same format as
Task 2.
Show the results to a TA.