0% found this document useful (0 votes)
2 views38 pages

Chapter_7

Uploaded by

Asma Mohammed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views38 pages

Chapter_7

Uploaded by

Asma Mohammed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Computer

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

 If you call readline() a second time, it returns the string "circus\n"

 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()

Converting File Input


 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)

• The newline character at the end of the line is ignored


when the string is converted to a numerical value 06/10/2025
Writing To A File
 For example, we can write the string "Hello, World!" to
our output file using the statement:

outfile.write("Hello, World!\n")

• Unlike print() when writing text to an output file, you


must explicitly write the newline character to start a
new line
• You can also write formatted strings to a file with the
write method:

outfile.write("Number of entries: %d\nTotal: %8.2f\n"


% (count, total))

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

 When using a String literal for a file name with path


information, you need to supply each backslash
twice:
infile = open("c:\\homework\\input.txt", "r")

• A single backslash inside a quoted string is the escape


character, which means the next character is
interpreted differently (for example, ‘\n’ for a newline
character)
• When a user supplies a filename into a program, the
user should not type the backslash twice

Pag
06/10/2025
e 11
Example
 Answer the following true or false questions related to the use of text files.

1. Executing the statement infile = open("", "r") will cause an error.

2. Executing the statement infile = open("input.txt", "w") will cause an error.

3. The following code will result in a run-time error:


infile = open("input.txt", "r")
line = infile.readline()
infile.close()
while line != "" :
print(line)
line = infile.readline()

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.

4. Close the file referenced by theFile.

5. Write the word Hello to the file referenced by out.

6. Close the output file referenced by out.


06/10/2025 13
Text Input and Output
 In the following sections, you will learn how to process text with complex contents, and
you will learn how to cope with challenges that often occur with real data
 Reading Words Example:

Mary had a little Mary


lamb input for line in inputFile : had
line = line.rsplit() output a
little
• There are times when you want to read input by: lamb
• Each word
• Each line
• A single character

• Python provides methods such: read(), split() and strip() for these tasks

Processing text input is required for almost all types


of programs that interact with the user
Pag
06/10/2025
e 14
Text Input and Output
 Python can treat an input file as though it were a container of strings in which each line
comprises an individual string
 For example, the following loop reads all lines from a file and prints them:

for line in infile :


print(line)
• At the beginning of each iteration, the loop variable line is assigned the value of a
string that contains the next line of text in the file
• There is a critical difference between a file and a container:
• Once you read the file you must close it before you can iterate over it again

• 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:

• This results in 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?

infile = open("input.txt", "r")


for word in infile :
word = word.rstrip()
print(word)

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:

• It will be split into 5 substrings that are stored in a list in


the same order in which they occur in the string:

 Notice that the last word in the line contains a comma


word = word.rstrip(".,?!")
 If we only want to print the words contained in the file
without punctuation marks, we can strip those from the
substrings using the rstrip() method introduced in the
previous section: 06/10/2025
Reading Words: Complete Example

inputFile = open("lyrics.txt", "r")


for line in inputFile :
line = line.rstrip()
wordList = line.split()
for word in wordList :
word = word.rstrip(".,?!")
print(word)

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)

• If the end of the file is reached, it returns an empty string ""

Algorithm: Reading Characters


while char != "" :
Process character
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:

For each record in the file


Read the entire record
Process the record

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

 One approach for reading records in this format is to read


the line, then search for the first digit in the string
returned by readline():
i = 0
char = line[0]
while not line[0].isdigit() :
i = i + 1

• You can then extract the country name and population


as substrings using the slice operator:

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

 What is printed by the following code segment?

line = "hello world!"


parts = line.split()
print(parts)

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

You might also like