Chapter 10 — Files An I

An Introduction to STEM Programming with Python -- 2019-09-03a Chapter 10 -- Files

Chapter 10 -- Files

Free Introduction

Page 117

eBook While working with computers, we all have worked with files and directories. A file is "a collection of

data or information that has a name."8 We can use files to store programs, text, and other structured information.

Throughout this chapter you will see files referred to as streams. You can think of a sequence of data arriving on a conveyor belt or like water in a stream. The file input/output methods we will be

Edition describing will work for many types of stream data. NOTE: If you are using the "grader" online system, you MUST include the line "from BrowserFile import open" at the top of your program. The BrowserFile module uses the browser's persistent storage to store the data read from and written to a file. This is required because a browser app written in JavaScript can't directly access files on the computer.

Please Objectives support this work at

Upon completion of this chapter's exercises, you should be able to: ? Employ files to retrieve and store plain text.

? ? ? ?

Demonstrate different methods for reading sequential data. Modify an existing file to add new data to the end of it. Use Python's context manager to manage a finite resource. Utilize data in the CSV format in a program.

Free

Prerequisites

This Chapter requires...

eBook

Edition Save Text to a File

The first operation we will do with a file, is to create one. There are three basic operations required to

8 retrieved 2017-04-13

Copyright 2019 -- James M. Reneau Ph.D. -- -- This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

An Introduction to STEM Programming with Python -- 2019-09-03a Chapter 10 -- Files

Page 118

do this: 1) open the file, 2) write the data to the file, and 3) close the file.

Free When opening a file that is stored in the same folder as our Python program, we need just its name. If

the file is stored in another location on the computer we need to specify the location and name of the file, this is called its path. The examples in this chapter will not add the complexity of storing files in other locations.

eBook The first step in creating a file is opening it. To open a file we use the open function and pass it the file

name or path and how we want to use the file. The most common file modes are 'r' for reading, 'w' for writing, and 'a' for appending new data.

open(file_path, mode)

Function

Open a file at the specified path and return a file object.

Edition The mode is a string that specifies how the file is to be handled. Modes include:

Mode Operation

'r'

Open a text file for reading. The file pointer will be placed at the

beginning of the file.

Please support this work at 'w'

Create a new empty file for writing. If the file exists, clear the file.

'a'

Open a file for writing but preserve the existing data. The file pointer will

be at the end of the file so that we can add new data.



Free The second thing we need to do is to write the data out to the stream. This is done with the write

method on the file object. When writing lines of text, the system does not automatically add an end of line (EOL) character. In the example below you can see the strings have '\n' in them, which is the EOL character.

eBook file.write(string)

Write a string to the file object. If a new line is needed be sure to append the "\n" character, or do a second write with it.

Method of file



Edition All file operations should be closed, when we are finished with the file. On most systems, input/output

(I/O) operations are stored on the computer's memory and may not be written immediately to the hard disk. This is known as caching and speeds up disk access. In Python, we use the close method on the file object to finalize the disk operation and to release the system resources.

Copyright 2019 -- James M. Reneau Ph.D. -- -- This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

An Introduction to STEM Programming with Python -- 2019-09-03a Chapter 10 -- Files

Page 119

Free file.close()

Method of file

Commit the changes to the file, if there are any, and release the operating resources.



eBook 1| ##### output a text file 2| ##### Text of Moby Dick, by Herman Melville, 3| ##### downloaded from Project Guttenberg 4| path = "mobydick.txt" 5| f = open(path,"w") 6| f.write("Call me Ishmael.\n")

Edition 7| f.write("Some years ago--never mind how long precisely--having little or no money in my purse, and nothing particular to interest me on shore,") 8| f.write(" I thought I would sail about a little and see the watery part of the world.\n") 9| f.write("It is a way I have of driving off the spleen and

Please support this work at regulating the circulation.\n")

10| f.close() 11| print(path, "written")

Text of Moby Dick, by Herman Melville, downloaded from Project Guttenberg.9

Free Using a Context Manger

Python allows for objects to create a special context at run-time. When objects have been created to take advantage of this feature, you can use the with statement to create and automatically finalize or

close them. All the input/output examples in this chapter and the remainder of this book will perform

these operations in a with context.

with object(...) as variable: suite

eBookStatement

The with statement wraps a suite of code into a managed context. Exception handling

(using try/except) may be kept local to errors within the block. By using a context

Edition manager, it insures that the object is closed once the suite is complete.



9

Copyright 2019 -- James M. Reneau Ph.D. -- -- This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

An Introduction to STEM Programming with Python -- 2019-09-03a Chapter 10 -- Files

Page 120

Free The following program re-writes the program that creates the Moby Dick text file, using a context

manager. It is the preferred way to do input/output.

1| ##### output a text file ? THE BETTER WAY 2| ##### Text of Moby Dick, by Herman Melville,

3| ##### downloaded from Project Guttenberg

eBook 4| fn = "mobydick.txt"

5| with open(fn,"w") as f:

6|

f.write("Call me Ishmael.\n")

7|

f.write("Some years ago--never mind how long precisely--having

little or no money in my purse, and nothing particular to

interest me on shore,")

8|

f.write(" I thought I would sail about a little and see the

Edition watery part of the world.\n")

9|

f.write("It is a way I have of driving off the spleen and

regulating the circulation.\n")

10| print(fn, "written")

Please support Read Text from a File this work at

Using for

Free The easiest way to read the lines from a text file is to use the for statement. If we open a file for reading

"r", we can simply treat the file object like a list and get each string (line) directly from the file. In the example above, the variable line will be set to each line. Remember a line may be written out by multiple calls to write and ends when we find a newline "\n".

1| with open("mobydick.txt") as file:

2|

for line in file:

3|

print("line=", line)

line= Call me Ishmael.

eBook

line= Some years ago--never mind how long precisely--having little

or no money in my purse, and nothing particular to interest me

Edition on shore, I thought I would sail about a little and see the

watery part of the world.

line= It is a way I have of driving off the spleen and regulating the circulation.

Copyright 2019 -- James M. Reneau Ph.D. -- -- This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

An Introduction to STEM Programming with Python -- 2019-09-03a Chapter 10 -- Files

Page 121

Free When a line is read in it will contain the "\n" new line character on the end. You may want to use the

.rstrip() string method to remove it.

1| with open("mobydick.txt") as file:

2|

for line in file:

3|

line = line.rstrip()

eBook 4|

print("line=", line)

Using readline

You may also use the readline method of the file to read one line at a time. The newline character

Edition will be included on the end of all lines that are successfully read, even blank ones. When newline

reaches the end of the file an empty string will be returned, signaling the end.

file.readline()

Method of file

Read the file up-to and including the new line character and return it as a string. If the

Please support this work at stream is at its end, return an empty string.



1| with open("mobydick.txt") as file:

2|

line = file.readline()

3|

while line:

4|

line = line.rstrip()

5|

print("line=", line)

6|

line = file.readline()

Free

Appending Text to a File

eBook In addition to writing to a new file and reading from a file, it is often necessary to add additional data to

the end of a file. We call that process appending. The open function has a mode "a" that opens a file for writing, leaves the existing data, and moves the write pointer to the end.

Edition 1| ###### append to a text file

2| ##### Text of Moby Dick, by Herman Melville, 3| ##### downloaded from Project Guttenberg 4| fn = "mobydick.txt" 5| with open(fn,"a") as stream:

Copyright 2019 -- James M. Reneau Ph.D. -- -- This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download