Digression: Scoring Matrices
Lecture 13
File Processing Part I
L13 File Processing Part I – 2
Objectives
• To understand how to format strings
• To understand the basic text file processing
concepts in Python.
• To learn how to read and write text files in
Python and string formatting
L13 File Processing Part I – 3
Revision
• What is printed when the code is executed ?
L13 File Processing Part I – 4
String Formatting
>>> amount = 1.50
>>> print(amount)
1.5
• If the code about is meant to represent an amount in dollars
and cents, we conventionally do not use fractional dollars but
rather dollars with 2 digits for cents
• Use the format method
>>> print(“${0:0.2f} change”.format(amount))
$1.50 change
• The first part is the string to be printed, called the template
string. The part between {} is the format specifier (where the
value is to be inserted and how it should look).
L13 File Processing Part I – 5
String Formatting
“${0:0.2f} change”.format(amount)
• The template contains a single specifier slot
with the description: 0:0.2f
• Form of description: • Index tells which parameter to insert into the L13 File Processing Part I – 6 String Formatting Looking at 0.2f • f means “fixed point” number • • ‘Compare 3.14 and 3.1400000000000001243’ L13 File Processing Part I – 7 String Formatting Example for j in range(11) : print() A basic child’s Needs modification to L13 File Processing Part I – 8 Multiline Strings ways to do this: – “Twas brillig, and the slithy toves\nDid gyre • Multiline string: • ”’ single quotes are also available L13 File Processing Part I – 9 Files: Multi-line Strings • A file is a sequence of data that is stored in – Files don’t disappear when program ends • Files can contain any data type, but the easiest to • A file usually contains more than one line of text. • Python uses the standard newline character (\n) to L13 File Processing Part I – 10 File Processing • The process of opening a file involves associating a • We can manipulate the file by manipulating this – Read from the file – Write to the file L13 File Processing Part I – 11 File Processing • When you’ve finished working with the file, it needs – Closing the file causes any outstanding • In some cases, not properly closing a file could result – Think of safely ejecting your memory stick L13 File Processing Part I – 12 File Processing – Reading • Reading a file into a program, e.g. word stored in memory, not on the disk. L13 File Processing Part I – 13 File Processing – Writing • Saving a file, i.e. data in RAM onto file – The original file on the disk is reopened in a mode – File writing operations copy the version of the – The file is closed L13 File Processing Part I – 14 File Processing in Python • Working with text files in Python – Associate a disk file with a file object using the open – – infile = open(“numbers.dat”, “r”) L13 File Processing Part I – 15 File Methods • • • L13 File Processing Part I – 16 File Processing # Prints a file to the screen. def main(): fname = input(“Enter filename: “) infile = open(fname,’r’) data = infile.read() infile.close() print(data) • First, prompt the user for a file name variable data L13 File Processing Part I – 17 File Processing • readline can be used to read the next line from a line = infile.readline() • This reads the first 5 lines of a file the ends of the lines L13 File Processing Part I – 18 File Processing Loop • Python treats the file itself as a sequence of # process the line here • Most efficient way to read through (and L13 File Processing Part I – 19 File Processing • Opening a file for writing prepares the file to • If you open an existing file for writing, you outlife.write( May use writelines() for writing sequence L13 File Processing Part I – 20 Summary • We learned how to format a string for output that is • We learned how to read files – All at once • We learned how to write into files Lecture 13�File Processing Part I
slot (there can be more than one). In this case,
amount (numbered from 0)
• The formatting specifier has the form:
the value. 0 means to use as much space as
necessary.
>>> “Compare {0} and {0:0.20f}”.format(3.14)
# Print out a child’s multiplication table 0..10
def multiplication_table() :
for i in range(11) :
print(“{0:0d} x {1:0d} = {2:0d}”.format(i, j, i*j))
multiplication table to
illustrate string
formatting.
properly resemble table,
e.g. numbers along top
and down left hand side
• You sometimes need strings that span more than one line. Two
• Embedded ‘\n’ in single string
and gimble in the wabe\nAll mimsy were the
borogoves\nAnd the mome raths outgrabe.”
“””Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!”””
• “hello\tworld”
• ‘\t’ is the tab character
secondary memory (disk drive).
work with are text.
mark line breaks.
file on disk with variable in memory.
variable.
to be closed.
operations and other bookkeeping for the file to
be completed.
in data loss.
processor
– File opened
– Contents read into RAM
– File closed
– Changes to the file are made to the copy
that will allow writing (this actually erases the
old contents unless specifically appending)
document in memory to the disk
function
disk. The
on whether we are reading, writing or appending the
file. You can also add ‘+’ in mode to mention both
read and write operations.
contents of the file as a single (possibly large, multi-
line) string. Watch out for final \n
file. This is all text up to and including the next
newline character
remaining lines in the file. Each list item is a single
line including the newline characters.
# printfile.py
• Open the file for reading
• The file is read as one string and stored in the
file, including the trailing newline character
infile = open(someFile, “r”)
for i in range(5):
print(line[:-1])
• Slicing is used to strip out the newline characters at
lines!
infile = open(someFile, “r”)
for line in infile:
infile.close()
process) file
– Multiple calls to readline() is inefficient
receive data
wipe out the file’s contents. If the named file
does not exist, a new one is created.
outfile = open(“mydata.out”, “w”)
(list) of strings
more readable and looks nice
– Single lines
– All the lines, line-by-line
Objectives
Revision
String Formatting
String Formatting
String Formatting
String Formatting Example
Multiline Strings
Files: Multi-line Strings
File Processing
File Processing
File Processing – Reading
File Processing – Writing
File Processing in Python
File Methods
File Processing
File Processing
File Processing Loop
File Processing
Summary