SlideShare a Scribd company logo
An Introduction To Software
Development Using Python
Spring Semester, 2014
Class #19:
Files, Part 1
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
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
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
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
Opening / Closing Files Syntax
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
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
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
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
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
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
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
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
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
What’s In Your Python Toolbox?
print() math strings I/O IF/Else elif While For
Lists And/Or/Not Functions Files
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/
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/

More Related Content

PPTX
Reading and Writing Files
PPT
ASP.NET Session 7
PPTX
Filehandling
PPTX
File handling in vb.net
PPT
File handling
PDF
input/ output in java
PPTX
32sql server
PPTX
30csharp
Reading and Writing Files
ASP.NET Session 7
Filehandling
File handling in vb.net
File handling
input/ output in java
32sql server
30csharp

What's hot (19)

PDF
java.io - streams and files
PPTX
File Handling in Java Oop presentation
PPTX
CSV File Manipulation
PPT
Input output streams
PPTX
Java input output package
PPTX
Java Input Output (java.io.*)
DOCX
python file handling
PPTX
C# File IO Operations
PPTX
9 Inputs & Outputs
PDF
Basic i/o & file handling in java
PPTX
Data file handling in python introduction,opening & closing files
PPT
Java IO Package and Streams
PPTX
31cs
PDF
Javaiostream
PPT
Byte stream classes.49
PPT
Java Streams
PPT
Various io stream classes .47
java.io - streams and files
File Handling in Java Oop presentation
CSV File Manipulation
Input output streams
Java input output package
Java Input Output (java.io.*)
python file handling
C# File IO Operations
9 Inputs & Outputs
Basic i/o & file handling in java
Data file handling in python introduction,opening & closing files
Java IO Package and Streams
31cs
Javaiostream
Byte stream classes.49
Java Streams
Various io stream classes .47
Ad

Viewers also liked (16)

PPTX
An Introduction To Python - Graphics
PPTX
An Introduction To Python - FOR Loop
PPTX
An Introduction To Python - Nested Branches, Multiple Alternatives
PPTX
An Introduction To Python - Tables, List Algorithms
PPTX
An Introduction To Python - Lists, Part 1
PPTX
An Introduction To Software Development - Architecture & Detailed Design
PPTX
An Introduction To Python - Working With Data
PPTX
An Introduction To Python - Python, Print()
PPTX
An Introduction To Python - Lists, Part 2
PPTX
An Introduction To Python - WHILE Loop
PPTX
An Introduction To Python - Variables, Math
PPTX
An Introduction To Software Development - Software Support and Maintenance
PPTX
An Introduction To Python - Functions, Part 2
PPTX
An Introduction To Python - Dictionaries
PPTX
An Introduction To Software Development - Implementation
PPTX
An Introduction To Python - Python Midterm Review
An Introduction To Python - Graphics
An Introduction To Python - FOR Loop
An Introduction To Python - Nested Branches, Multiple Alternatives
An Introduction To Python - Tables, List Algorithms
An Introduction To Python - Lists, Part 1
An Introduction To Software Development - Architecture & Detailed Design
An Introduction To Python - Working With Data
An Introduction To Python - Python, Print()
An Introduction To Python - Lists, Part 2
An Introduction To Python - WHILE Loop
An Introduction To Python - Variables, Math
An Introduction To Software Development - Software Support and Maintenance
An Introduction To Python - Functions, Part 2
An Introduction To Python - Dictionaries
An Introduction To Software Development - Implementation
An Introduction To Python - Python Midterm Review
Ad

Similar to An Introduction To Python - Files, Part 1 (20)

PPT
ch09.ppt
PPTX
01 file handling for class use class pptx
PDF
Python file handling
PPTX
File handling in Python
PPTX
5-filehandling-2004054567151830 (1).pptx
PPTX
Python UNIT-III-part-1.pptx File Handling
PPTX
Files handling using python language.pptx
PPTX
Chapetr 4 C++ file object oriented programming
PPT
File Handling as 08032021 (1).ppt
PDF
Python-files
PPTX
IOStream.pptx
PDF
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
PPT
Python file handlings
PPTX
Files in Python.pptx
PPTX
Files in Python.pptx
PPTX
File handling
PPTX
Working with files in c++. file handling
PPT
File Handling Btech computer science and engineering ppt
PPT
Data file handling
PPTX
File Operations in python Read ,Write,binary file etc.
ch09.ppt
01 file handling for class use class pptx
Python file handling
File handling in Python
5-filehandling-2004054567151830 (1).pptx
Python UNIT-III-part-1.pptx File Handling
Files handling using python language.pptx
Chapetr 4 C++ file object oriented programming
File Handling as 08032021 (1).ppt
Python-files
IOStream.pptx
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
Python file handlings
Files in Python.pptx
Files in Python.pptx
File handling
Working with files in c++. file handling
File Handling Btech computer science and engineering ppt
Data file handling
File Operations in python Read ,Write,binary file etc.

Recently uploaded (20)

PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
PDF
Pre independence Education in Inndia.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PPTX
Pharma ospi slides which help in ospi learning
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PPTX
Introduction and Scope of Bichemistry.pptx
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Open folder Downloads.pdf yes yes ges yes
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PDF
Module 3: Health Systems Tutorial Slides S2 2025
O7-L3 Supply Chain Operations - ICLT Program
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
Pre independence Education in Inndia.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Open Quiz Monsoon Mind Game Prelims.pptx
Pharma ospi slides which help in ospi learning
The Final Stretch: How to Release a Game and Not Die in the Process.
Week 4 Term 3 Study Techniques revisited.pptx
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Introduction and Scope of Bichemistry.pptx
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Open folder Downloads.pdf yes yes ges yes
102 student loan defaulters named and shamed – Is someone you know on the list?
NOI Hackathon - Summer Edition - GreenThumber.pptx
Module 3: Health Systems Tutorial Slides S2 2025

An Introduction To Python - Files, Part 1

  • 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
  • 6. Opening / Closing Files Syntax
  • 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

  • #2: 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.