This presentation is a part of the COP2271C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce Freshmen students to both the process of software development and to the Python language.
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
A video of Dr. Anderson using these slides is available on YouTube at:
http://youtu.be/YD5Yk6cNsdE
1. An Introduction To Software
Development Using Python
Spring Semester, 2014
Class #19:
Files, Part 1
2. Data, Data, Data
• In the real world, your program will need to process data. A
lot of data.
• In this class we’ve already used two different ways to get data
into your programs:
– You typed it in (“input”)
– It was given to you in the form of a list (patients)
• Now it’s time to deal with A LOT OF DATA.
• Say hello to files…
Image Credit: paulmjohnstone.wordpress.com
3. Opening Files: Reading
• To access a file, you must first open it.
• When you open a file, you give the name of the file, or, if the
file is stored in a different directory, the file name preceded
by the directory path.
• You also specify whether the file is to be opened for reading
or writing.
• Suppose you want to read data from a file named input.txt,
located in the same directory as the program. Then you use
the following function call to open the file:
infile = open("input.txt", "r")
Image Credit: www.clipartof.com
4. Opening Files: Writing
• This statement opens the file for reading (indicated by the
string argument "r") and returns a file object that is associated
with the file named input.txt.
• The file object returned by the open function must be saved
in a variable.
• All operations for accessing a file are made via the file object.
• To open a file for writing, you provide the name of the file as
the first argument to the open function and the string "w" as
the second argument:
outfile = open("output.txt", "w")
Image Credit: www.freepik.com
5. Closing A File
• If the output file already exists, it is emptied before the new data is
written into it.
• If the file does not exist, an empty file is created.
• When you are done processing a file, be sure to close the file using the
close method:
infile.close()
outfile.close()
• If your program exits without closing a file that was opened for writing,
some of the output may not be written to the disk file.
• After a file has been closed, it cannot be used again until it has been
reopened.
Image Credit: www.clipartpanda.com
7. Reading From A File
• To read a line of text from a file, call the readline method with
the file object that was returned when you opened the file:
line = infile.readline()
• When a file is opened, an input marker is positioned at the
beginning of the file.
• The readline method reads the text, starting at the current
position and continuing until the end of the line is
encountered.
• The input marker is then moved to the next line.
Image Credit: www.clipartpanda.com
8. Reading From A File
• The readline method returns the text that it read, including the newline
character that denotes the end of the line.
• For example, suppose input.txt contains the lines
flying
circus
• The first call to readline returns the string "flyingn".
• Recall that n denotes the newline character that indicates the end of the
line.
• If you call readline a second time, it returns the string "circusn".
• Calling readline again yields the empty string "" because you have reached
the end of the file. Image Credit: fanart.tv
9. Blank Lines
• If the file contains a blank line, then readline returns a string containing
only the newline character "n".
• Reading multiple lines of text from a file is very similar to reading a
sequence of values with the input function.
• You repeatedly read a line of text and process it until the sentinel value is
reached:
line = infile.readline()
while line != "" :
Process the line.
line = infile.readline()
• The sentinel value is an empty string, which is returned by the readline
method after the end of file has been reached.
Image Credit: all-free-download.com
10. What Are You Reading?
• As with the input function, the readline method can
only return strings.
• If the file contains numerical data, the strings must
be converted to the numerical value using the int or
float function:
value = float(line)
• Note that the newline character at the end of the
line is ignored when the string is converted to a
numerical value.
Image Credit: retroclipart.co
11. Writing To A File
• You can write text to a file that has been opened for writing.
This is done by applying the write method to the file object.
• For example, we can write the string "Hello, World!" to our
output file using the statement:
outfile.write("Hello, World!n")
• The print function adds a newline character at the end of
its output to start a new line.
• When writing text to an output file, however, you must
explicitly write the newline character to start a new line.
Image Credit: olddesignshop.com
12. Writing To A File
• The write method takes a single string as an argument and
writes the string immediately.
• That string is appended to the end of the file, following any
text previously written to the file.
• You can also write formatted strings to a file with the write
method:
outfile.write("Number of entries: %dnTotal: %8.2fn" %
(count, total))
Image Credit: www.freeclipartnow.com
13. Writing With The Print Statement
• Alternatively, you can write text to a file with the print
function.
• Supply the file object as an argument with name file, as
follows:
print("Hello, World!", file=outfile)
• If you don’t want a newline, use the end argument:
print("Total: ", end="", file=outfile)
Image Credit: www.artofmanliness.com
14. File I/O Example
• Suppose you are given a text file that contains a sequence of floating-point
values, stored one value per line. You need to read the values and write
them to a new output file, aligned in a column and followed by their total
and average value.
32.0
54.0
67.5
80.25
115.0
32.00
54.00
67.50
80.25
115.00
--------
Total: 348.75
Average: 69.75
Input File Output File
15. One Final Note: Backslashes
• When you specify a file name as a string literal, and the name
contains backslash characters (as in a Windows file name),
you must supply each backslash twice:
infile = open("c:homeworkinput.txt", "r")
• A single backslash inside a quoted string is an escape
character that is combined with the following character to
form a special meaning, such as n for a newline character.
• The combination denotes a single backslash.
• When supplying a file name to a program, however, a
program user should not type the backslash twice.
Image Credit: www.pageresource.com
16. What’s In Your Python Toolbox?
print() math strings I/O IF/Else elif While For
Lists And/Or/Not Functions Files
17. What We Covered Today
1. Opening files
2. Reading from files
3. Writing to files
4. Closing files
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
18. What We’ll Be Covering Next Time
1. Files, Part 2
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/
Editor's Notes
New name for the class
I know what this means
Technical professionals are who get hired
This means much more than just having a narrow vertical knowledge of some subject area.
It means that you know how to produce an outcome that I value.
I’m willing to pay you to do that.