Chapter_7
Chapter_7
Programming
Chapter 7
Prepared Mohammed Esmaail Shakfah 1
Spring 2024
06/10/2025
Contents
Reading and Writing Text Files
Text Input and Output
Pag
06/10/2025
e2
Reading and Writing Text Files
Text files are very commonly used to store information
They are the most ‘portable’ types of data files
Examples of text files include files that are created with a simple text editor, such as
Windows Notepad, and Python source code and HTML files
Opening Files: Reading Opening Files: Writing
To access a file, you must first open it
To open a file for writing, you provide the name
of the file as the first argument to the open
Suppose you want to read data from a file named
function and the string "w" as the second
input.txt, located in the same directory as the argument:
program outfile = open("output.txt",
To open a file for reading, you must provide the "w")
• If the output file already exists, it is emptied
name of the file as the first argument to the open
function and the string "r" as the second before the new data is written into it
argument: • If the file does not exist, an empty file is created
infile = open("input.txt",
"r") When you are done processing a file, be sure to
Important things to keep in mind: close the file using the close() method:
When opening a file for reading, the file must exist
(and otherwise be accessible) or an exception infile.close()
occurs outfile.close()
The file object returned by the open function must
be saved in a variable • If your program exits without closing a file that was
opened for writing, some of the output may not be
All operations for accessing a file are made via
written to the disk file
the file object
Syntax: Opening And Closing Files
Pag
06/10/2025
e4
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
For example, suppose input.txt contains the lines
flying
circus
The first call to readline() returns the string "flying\n"
Recall that \n denotes the newline character that indicates the end of the line
Calling readline() again yields the empty string "" because you have reached the end of the file
If the file contains a blank line, then readline() returns a string containing only the newline
character "\n"
06/10/2025
Reading Multiple Lines From a File
You repeatedly read a line of text and process it until the sentinel value is reached:
The sentinel value is an empty string, which is returned by the readline() method after the
end of file has been reached
line = infile.readline()
while line != "" :
# Process the line.
line = infile.readline()
outfile.write("Hello, World!\n")
Pag
06/10/2025
e7
Example: File Reading/Writing
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
If the input file has the contents
32.0
54.0
67.5
80.25
115.0
Pag
06/10/2025
e8
Example: File Reading/Writing (2)
The output file will contain
32.00
54.00
67.50
80.25
115.00
--------
Total: 348.75
Average: 69.75
Pag
06/10/2025
e9
Pag
06/10/2025
e 10
Common Error
Backslashes in File Names
Pag
06/10/2025
e 11
Example
Answer the following true or false questions related to the use of text files.
4. The following code works correctly to write the string "Hello, World!" to the text file
output.txt.
06/10/2025 12
outfile = open("output.txt", "r")
Example
Write statements to carry out the following tasks:
1. Open the text file out.txt for writing and assign the file object to the variable outfile.
2. Read the first line of text from the file referenced by infile and store it in variable data.
3. Read an integer value from the next line of the file referenced by infile and store it in
value.
• Python provides methods such: read(), split() and strip() for these tasks
• We have a file that contains a • When the lines of input are printed to the terminal, they
collection of words; one per line: will be displayed with a blank line between each word:
spam
• spam
and
eggs • and
Pag
06/10/2025
e 15
• eggs
Removing The Newline
Recall that each input line ends with a newline (\n) character
Generally, the newline character must be removed before the input string is used
When the first line of the text file is read, the string line contains
line = line.rstrip()
To remove the newline character, apply the rstrip() method to the string:
Pag
06/10/2025
e 16
Character Strip Methods
Pag
06/10/2025
e 17
Character Strip Examples
Pag
06/10/2025
e 18
Example
If the text file input.txt contains the following contents
apple
pear
banana
what is printed by the following code segment?
06/10/2025 19
Reading Words
Sometimes you may need to read the individual words from a text file
For example, suppose our input file contains two lines of text
Mary had a little lamb,
whose fleece was white as snow
We would like to print to the terminal, one word per line
Mary
had
a
little
...
Because there is no method for reading a word from a
file, you must first read a line and then split it into
individual words
line = line.rstrip()
wordlist = line.split()
Pag
06/10/2025
e 20
Reading Words
The split method returns the list of substrings that
results from splitting the string at each blank space
For example, if line contains the string:
inputFile.close()
Pag
06/10/2025
e 22
Example Two
Pag
06/10/2025
e 23
Example Two
Pag
06/10/2025
e 24
Additional String Splitting Methods
Pag
06/10/2025
e 25
Additional String Splitting Examples
Pag
06/10/2025
e 26
Example
What is printed by the following code segment, if the file object infile refers to a file
that contains one line of text: 1600 Pennsylvania Avenue NW, Washington, DC 20500?
count = 0
line = infile.readline()
line = line.rstrip()
wordList = line.split()
for word in wordList :
count = count + 1
print(count)
06/10/2025 27
Reading Characters
The read() method takes a single argument that specifies the number of characters
to read
The method returns a string containing the characters
When supplied with an argument of 1, the read() method returns a string consisting
of the next character in the file
char = inputFile.read(1)
Pag
06/10/2025
e 28
Reading Records
A text file can contain a collection of data records in which each record consists of
multiple fields
For example, a file containing student data may consist of records composed of an
identification number, full name, address, and class year
When working with text files that contain data records, you generally have to read the
entire record before you can process it:
Pag
06/10/2025
e 29
Record Formats: Example
The organization or format of the records can vary, however, making some
formats easier to read than others
A typical format for such data is to store each field on a separate line of the
file with all fields of a single record on consecutive lines:
China
1330044605
India
1147995898
United States
303824646
...
Pag
06/10/2025
e 30
Record Formats: Example
Reading the data in this format is rather easy
Because each record consists of two fields, we read two lines from the file
for each record
line = infile.readline()
while line != "" :
countryName = line.rstrip()
line = infile.readline()
population = int(line)
Process data record
line = infile.readline()
Pag
06/10/2025
e 31
Record Formats: Example 2
Another common format stores each data record on a single line
If the record’s fields are separated by a specific delimiter “:” you can
extract the fields by splitting the line with the split() method
China:1330044605
India:1147995898
United States:303824646
...
But what if the fields are not separated by a delimiter?
China 1330044605
India 1147995898 inputString = "United States 303824646"
United States 303824646 result = inputString.rsplit(" ",1)
... print(result)
Because some country names have more than one
word, we cannot simply use a blank space as the
delimiter because multi-word names would be split
incorrectly Pag
06/10/2025
e 32
Can we use rsplit in this case?
Record Formats: Example 3
countryName = line[0 : i - 1]
population = int(line[i : ])
Pag
06/10/2025
e 33
Record Formats: Example 3
‘Slicing’ the string read from file
Pag
06/10/2025
e 34
File Operations
Pag
06/10/2025
e 35
1
06/10/2025 36
Example
06/10/2025 37
Example
Suppose the input file contains the single line of text
6E4 6,995.00
What are the values of each of the expressions after the following code segment is
executed? If an error occurs, enter an "error" for the value.
line = infile.readline()
parts = line.split()
x1 = float(parts[0])
x2 = float(parts[1])
1- len(parts)
2- x1
3- x2
06/10/2025 38