Chapter 6 - Files: Textbook

Ace your homework & exams now with Quizwiz!

What is a record? What is a field?

A record is a complete set of data that describes one item, and a field is a single piece of data within a record.

If an existing file is opened in append mode, what happens to the file's existing contents?

It will not be erased and new data will be written at the end of the file's current contents.

What is a record?

a complete set of data about an item

This is a single piece of data within a record. a. field b. variable c. delimiter d. subrecord

field

Three steps of files

# Open a file named philosophers.txt. 5 outfile = open('philosophers.txt', 'w') 6 7 # Process Write the names of three philosphers 8 # to the file. 9 outfile.write('John Locke\n') 10 outfile.write('David Hume\n') 11 outfile.write('Edmund Burke\n') 12 13 # Close the file. 14 outfile.close()

Example of detecting end of file

# Open the sales.txt file for reading. sales_file = open('sales.txt', 'r') # Read the first line from the file, but # don't convert to a number yet. We still # need to test for an empty string. line = sales_file.readline() # As long as an empty string is not returned from readline, continue processing. while line != '': # Convert line to a float. amount = float(line) # Format and display the amount. ....print(format(amount, '.2f')) # Read the next line. line = sales_file.readline() # Close the file. sales_file.close() 1000.00 2000.00 3000.00 4000.00 5000.00

This program gets sales amounts for a series of days from the user and writes those amounts to a file named sales.txt. The user specifies the number of days of sales data he or she needs to enter. In the sample run of the program, the user enters sales amounts for five days.

# This program prompts the user for sales amounts # and writes those amounts to the sales.txt file. Output: For how many days do you have sales? 5 Enter the sales for day #1: 1000.0 Enter the sales for day #2: 2000.0 Enter the sales for day #3: 3000.0 Enter the sales for day #4: 4000.0 Enter the sales for day #5: 5000.0 Data written to sales.txt.

Example of for loop

# This program uses the for loop to read all of the values in the sales.txt file. # Open the sales.txt file for reading. sales_file = open('sales.txt', 'r') # Read all the lines from the file. for line in sales_file: # Convert line to a float. amount = float(line) # Format and display the amount. print(format(amount, '.2f')) # Close the file. sales_file.close() Program Output 1000.00 2000.00 3000.00 4000.00 5000.00

In what mode do you open a file if you want to write data to it, but you do not want to erase the file's existing contents?

'a' mode

Python file modes

'r' Open a file for reading only. The file cannot be changed or written to. customer_file = open('customers.txt', 'r') 'w' Open a file for writing. If the file already exists, erase its contents. If it does not exist, create it. sales_file = open('sales.txt', 'w') 'a' Open a file to be written to. All data written to the file will be appended to its end. If the file does not exist, create it. WARNING Remember, when you use the 'w' mode, you are creating the file on the disk. If a file with the specified name already exists when the file is opened, the contents of the existing file will be deleted.

In what mode do you open a file that you do not want the file to be changed or written to?

'r' mode

What three steps must be taken by a program when it uses a file?

1) Open the file 2) Process the file 3) Close the file

What is an input file?

A file from which a program reads data. It is called an input file because the program receives input from it.

What is an output file?

A file to which a program writes a data. It is called an output file because the program sends output to it.

What is a file's read position? Initially, where is the read position when an input file is opened?

A file's read position marks the location of the next item that will be read from the file. When an input file is opened, its read position is initially set to the first item in the file.

What is a file's read position? Where is the read position when a file is first opened for reading?

A special value known as a read position that is internally maintained for that file. A file's read position marks the location of the next item that will be read from the file. Initially, the read position is set to the beginning of the file.

When you write data to a file opened in 'a' mode, to what part of the file is the data written?

All data written to the file will be appended to its end.

What is the purpose of closing a file?

Closing a file disconnects the program from the file.

Why should a program close a file when it's finished using it?

Closing a file disconnects the program from the file. In some systems, failure to close an output file can cause a loss of data.

What is the purpose of closing a file?

Closing a file disconnects the program from the file. The process of closing an output file forces any unsaved data that remains in the buffer to be written to the file. In some systems, failure to close an output file can cause a loss of data.

Reading a String and Stripping the Newline

Each string in Python has a method named rstrip that removes, or "strips," specific characters from the end of a string. The following code shows an example of how the rstrip method can be used. name = 'Joanne Manchester\n' name = name.rstrip('\n') # Open a file named philosophers.txt. infile = open('philosophers.txt', 'r') # Read three lines from the file. line1 = infile.readline() line2 = infile.readline() line3 = infile.readline() # Strip the \n from each string. line1 = line1.rstrip('\n') line2 = line2.rstrip('\n') line3 = line3.rstrip('\n') # Close the file. infile.close() # Print the data that was read into # memory. print(line1) print(line2) print(line3) John Locke David Hume Edmund Burke Instead of John Locke David Hume Edmund Burke

If you do not handle an exception, it is ignored by the Python interpreter, and the program continues to execute. T or F

False

The else suite in a try/except statement executes only if a statement in the try suite raises an exception. T or F

False

The finally suite in a try/except statement executes only if no exceptions are raised by statements in the try suite. T or F

False

The process of opening a file is only necessary with input files. Output files are automatically opened when data is written to them. T or F

False

When a file that already exists is opened in append mode, the file's existing contents are erased. T or F

False

When working with a sequential access file, you can jump directly to any piece of data in the file without reading the data that comes before it. T or F

False

Using Loops to Process Files

Files usually hold large amounts of data, and programs typically use a loop to process the data in a file.

A program that allows him to enter the running time (in seconds) of each short video in a project. The running times are saved to a file.

Get the number of videos in the project. Open an output file. For each video in the project: Get the video's running time. Write the running time to the file. Close the file.

Reading Data From a File

If a file has been opened for reading (using the 'r' mode) you can use the file object's read method to read its entire contents into memory. When you call the read method, it returns the file's contents as a string. # Open a file named philosophers.txt. infile = open('philosophers.txt', 'r') # Read the file's contents. file_contents = infile.read() # Close the file. infile.close() # Print the data that was read into # memory. print(file_contents) John Locke David Hume Edmund Burke

If a file already exists what happens to it if you try to open it as an output file (using the ' w ' mode )?

If a file with the specified name already exists when the file is opened, the contents of the existing file will be erased.

A program that reads the contents of the file, displays the running times, and then displays the total running time of all the segments.

Initialize an accumulator to 0. Initialize a count variable to 0. Open the input file. For each line in the file: Convert the line to a floating-point number. (This is the running time for a video.) Add one to the count variable. (This keeps count of the number of videos.) Display the running time for this video. Add the running time to the accumulator. Close the file. Display the contents of the accumulator as the total running time.

Describe the three steps that must be taken when a file is used by a program.

Open file - Opening a file creates a connection between the file and the program. Opening an output file usually creates the file on the disk and allows the program to write data to it. Opening an input file allows the program to read data from the file. Process file - In this step data is either written to the file (if it is an output file) or read from the file (if it is an input file ). Close file - When the program is finished using the file, the file must be closed. Closing a file disconnects the file from the program.

In Python, the readline method returns an empty string ('') when it has attempted to read beyond the end of a file. This makes it possible to write a while loop that determines when the end of a file has been reached.

Open the file Use readline to read the first line from the file While the value returned from readline is not an empty string: Process the item that was just read from the file Use readline to read the next line from the file. Close the file NOTE in this algorithm, we call the readline method just before entering the while loop. The purpose of this method call is to get the first line in the file, so it can be tested by the loop. This initial read operation is called a priming read.

What three steps must be taken by a program when it uses a file?

Open the file Process the file Close the file

What is the purpose of opening a file?

Opening a file crates a connection between the file and the program. It also creates an association between the file and a file object.

Reading a File with a Loop and Detecting the End of the File

Quite often, a program must read the contents of a file without knowing the number of items that are stored in the file. For example, the sales.txt file can have any number of items stored in it, because the program asks the user for the number of days for which he or she has sales amounts. If the user enters 5 as the number of days, the program gets 5 sales amounts and writes them to the file. If the user enters 100 as the number of days, the program gets 100 sales amounts and writes them to the file. This presents a problem if you want to write a program that processes all of the items in the file, however many there are. For example, suppose you need to write a program that reads all of the amounts in the sales.txt file and calculates their total. You can use a loop to read the items in the file, but you need a way of knowing when the end of the file has been reached.

Two ways to access data stored in file

Sequential access: file read sequentially from beginning to end, can't skip ahead Direct access: can jump directly to any piece of data in the file

What are the two types of file access? What is the difference between these two?

Sequential and direct access. When you work with a sequential access file, you access data from the beginning of the file to the end of the file. When you work with a direct access file, you can jump directly to any piece of data in the file without reading the data that comes before it.

In general, what are the two types of file? What is the difference between these two types of files?

Text and binary. A text file contains data that has been encoded as text using a scheme such as ASCII. Even if the file file contains numbers, those numbers are stored in the file as a series of characters. As a result, the file may be opened and viewed in a text editor such as Notepad. A binary file contains data that has that has not been converted to text. As a consequence, you cannot view the contents of a binary file with a text editor

Processing Records

The data that is stored in a file is frequently organized in records. A record is a complete set of data about an item, and a field is an individual piece of data within a record.

If a file does not exist and a program attempts to open it in append mode, what happens?

The file will be created.

If a file already exists what happens to it if you try to open it as an output file (using the "w" mode)?

The file's contents are erased

When writing a program that performs an operation on a file, what two file-associated names do you have to work with in your code?

The file's name on the disk and the name of a variable that references a file object

What is a priming read? What is it's purpose?

The initial read operation. The purpose is to get the first line in the file, so it can be tested by the loop.

What does it mean when the readline method returns an empty string?

The realine method returns an empty string ("") when it has attempted to read beyond the end of a file.

When an input file is opened, its read position is initially set to the first item in the file. T or F

True

When you open a file that file already exists on the disk using the "w" mode, the contents of the existing file will be erased. T or F

True

You can have more than one except clause in a try/except statement. T or F

True

File Input/Output

When a program needs to save data for later use, it writes the data in a file. The data can be read from the file at a later time.

Appending Data to an Existing File

When you use the 'w' mode to open an output file and a file with the specified filename already exists on the disk, the existing file will be deleted and a new empty file with the same name will be created. Sometimes you want to preserve an existing file and append new data to its current contents. Appending data to a file means writing new data to the end of the data that already exists in the file. In Python, you can use the 'a' mode to open an output file in append mode, which means the following. If the file already exists, it will not be erased. If the file does not exist, it will be created. For example, assume the file friends.txt contains the following names, each in a separate line: Joe Rose Geri myfile = open('friends.txt', 'a') myfile.write('Matt\n') myfile.write('Chris\n') myfile.write('Suze\n') myfile.close() After this program runs, the file friends.txt will contain the following data: Joe Rose Geri Matt Chris Suze

Describe the way that you use a temporary file in a program that modifies a record in a sequential access file.

You copy all of the original file's records to the temporary file, but when you get to the record that is to be modified, you do not write its old contents to the temporary file. Instead, you write its new modified values to the temporary file. Then, you finish copying any remaining records from the original file to the temporary file. The temporary file then takes the place of the original file. You delete the original file and rename the temporary file, giving it the name that the original file had on the computer's disk.

Describe the way that you use a temporary file in a program that deletes a record from a sequential file.

You copy all of the original file's records to the temporary file, except for the record that is to be deleted. The temporary file then takes the place of the original file. You delete the original file and rename the temporary file, giving it the name that the original file had on the computer's disk.

Describe the way that you use a temporary file in a program that modifies a record in a sequential access file

You copy all the original file's records to the temporary file, but when get to the record that is to be modified you do not write its old contents to the temporary file. Instead, you write its new modified values to the temporary file. Then you finish copying any remaining records from the original file to the temporary file.

Describe the way that you use a temporary file in a program that deletes a record from a sequential file.

You copy all the original file's records to the temporary file, except for the record that is to be deleted. The temporary file then takes the place of the original file. You delete the original file and rename the temporary file, giving it the name that the original file had on the computer's disk.

In what mode do you open a file if you want to write data to it, but you do not want to erase the file's existing contents? When you write data to such a file, to what part of the file is the data written?

You open the file in append mode. When you write data to a file in append mode, the data is written to the end of the file's existing contents.

What is the purpose of opening a file?

You use the open function in Python to open a file. The open function creates a file object and associates it with a file on the disk.

Opening a file

You use the open function in Python to open a file. The open function creates a file object and associates it with a file on the disk. file_variable = open(filename, mode)

What is an input file?

a file that data is read from. It is called an input file because the program gets input from the file.

What is an output file?

a file that data is written to. It is called an output file because the program stores output in it.

What is the difference between sequential access and direct access files?

a sequential access file, you access data from the beginning of the file to the end of the file. If you want to read a piece of data that is stored at the very end of the file, you have to read all of the data that comes before it - you cannot jump directly to the desired data. a direct access file (which is also known as a random access file), you can jump directly to any piece of data in the file without reading the data that comes before it

What is a field?

an individual piece of data within a record

What is a file object?

an object that is associated with a specific file and provides a way for the program to work with that file.

When a file is opened in this mode, data will be written at the end of the file's existing contents. a. output mode b. append mode c. backup mode d. read-only mode

append mode

Two Types of Files

binary and text

This type of file contains data that has not been converted to text. a. text file b. binary file c. Unicode file d. symbolic file

binary file

This is a small "holding section " in memory that many systems write data to before writing the data to a file. a. buffer b. variable c. virtual file d. temporary file

buffer

When a program is finished using a file, it should do this. a. erase the file b. open the file c. close the file d. encrypt the file

close the file

When working with this type of file, you can jump directly to any piece of data in the file without reading the data that comes before it. a. ordered access b. binary access c. direct access d. sequential access

direct access

This is a section of code that gracefully responds to exceptions. a. exception generator b. exception manipulator c. exception handler d. exception monitor

exception handler

Concatenating a Newline to a String

file.write(variable + '\n') print('Enter the names of three friends.') name1 = input('Friend #1: ') name2 = input('Friend #2: ') name3 = input('Friend #3: ') # Open a file named friends.txt. myfile = open('friends.txt', 'w') # Write the names to the file. myfile.write(name1 + '\n') myfile.write(name2 + '\n') myfile.write(name3 + '\n') # Close the file. myfile.close() print('The names were written to friends.txt.') Enter the names of three friends. Friend #1: Joe Friend #2: Rose Friend #3: Geri The names were written to friends.txt. equivalent to (Joe/nRose/nGeri/n)

When writing a program that performs an operation on a file, what two file associated names do you have to work with in your code?

file_variable and filename file_variable is the name of the variable that will reference the file object. filename is a string specifying the name of the file.

File Opening Format

file_variable is the name of the variable that will reference the file object. filename is a string specifying the name of the file. mode is a string specifying the mode (reading, writing, etc.) in which the file will be opened. mode w, r, a file_variable = open(filename, mode)

Writing Data to a File

file_variable.write(string) In the format, file_variable is a variable that references a file object, and string is a string that will be written to the file. The file must be opened for writing (using the 'w' or 'a' mode) or an error will occur. Let's assume customer_file references a file object, and the file was opened for writing with the 'w' mode. Here is an example of how we would write the string 'Charles Pace' to the file: customer_file.write('Charles Pace') or name = 'Charles Pace' customer_file.write(name) then customer_file.close()

Assume that the file data.txt exists and contains several lines of text. Write a short program using the while loop that displays each line in the file.

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

Revise the program that you wrote for Chkpnt 6.14 to use the for loop instead of a while loop

infile = open('data.txt', 'r') for line in infile: print(line) infile.close()

A file that data is read from is known as a(n) a. input file. b. output file. c. sequential access file. d. binary file.

input file

What does it mean when the readline method returns an empty string?

it has attempted to read beyond the end of a file.

What is a file's read position? Initially, where is the read position when an input file is opened?

it marks the location of the next item that will be read from the file. When a file is opened for reading, a special value known as a read position is internally maintained for that file. Initially, the read position is set to the beginning of the file.

Before a file can be used by a program, it must be a. formatted. b. encrypted. c. closed. d. opened.

opened

Write a short program that uses a for loop to write the numbers 1 through 10 to a file

outfile = open("numbers.txt", "w") for num in range(1,11) outfile.write(str(num) + "\n") outfile.close()

A file that data is written to is known as a(n) a. input file. b. output file. c. sequential access file. d. binary file.

output file

When an exception is generated, it is said to have been _______ a. built b. raised c. caught d. killed

raised

ReadLine method

read method allows you to easily read the entire contents of a file with one statement In Python, you can use the readline method to read a line from a file. (A line is simply a string of characters that are terminated with a \n.) The method returns the line as a string # Open a file named philosophers.txt. 5 infile = open('philosophers.txt', 'r') 6 7 # Read three lines from the file. 8 line1 = infile.readline() 9 line2 = infile.readline() 10 line3 = infile.readline() 11 12 # Close the file. 13 infile.close() 14 15 # Print the data that was read into 16 # memory. 17 print(line1) 18 print(line2) 19 print(line3) John Locke David Hume Edmund Burke There's space like that because of the \n NOTE! If the last line in a file is not terminated with a \n, the readline method will return the line without a \n.

This marks the location of the next item that will be read from a file. a. input position b. delimiter c. pointer d. read position

read position

When working with this type of file, you access its data from the beginning of the file to the end of the file. a. ordered access b. binary access c. direct access d. sequential access

sequential access

What are the two types of file access?

sequential access and direct access

In general, what are the two types of files? What is the difference between these two types of files?

text and binary A text file contains data that has been encoded as text, using a scheme such as ASCII or Unicode. The file may be opened and viewed in a text editor such as Notepad. A binary file contains data that has not been converted to text. The data that is stored in a binary file is intended only for a program to read. You cannot view the contents of a binary file with a text editor.

The contents of this type of file can be viewed in an editor such as Notepad. a. text file b. binary file c. English file d. human-readable file

text file

You write this statement to respond to exceptions. a. run/ handle b. try/except c. try /handle d. attempt/except

try/except

Reading Numeric Data

use: infile = open('numbers.txt', 'r') value = int(infile.readline()) infile.close() When you read numbers from a text file, they are always read as strings. # Open a file for reading. infile = open('numbers.txt', 'r') # Read three numbers from the file. num1 = int(infile.readline()) num2 = int(infile.readline()) num3 = int(infile.readline()) # Close the file. infile.close() # Add the three numbers. total = num1 + num2 + num3 # Display the numbers and their total. print('The numbers are:', num1, num2, num3) print('Their total is:', total) The numbers are: 22 14 −99 Their total is: −63

Writing Numeric Data

use: outfile.write(str(num1) + '\n') Strings can be written directly to a file with the write method, but numbers must be converted to strings before they can be written. str converts a value to a string. For example, assuming the variable num is assigned the value 99, the expression str(num) will return the string '99' # Open a file for writing. 7 outfile = open('numbers.txt', 'w') 8 9 # Get three numbers from the user. 10 num1 = int(input('Enter a number: ')) 11 num2 = int(input('Enter another number: ')) 12 num3 = int(input('Enter another number: ')) 13 14 # Write the numbers to the file. 15 outfile.write(str(num1) + '\n') 16 outfile.write(str(num2) + '\n') 17 outfile.write(str(num3) + '\n') 18 19 # Close the file. 20 outfile.close() 21 print('Data written to numbers.txt') Enter a number: 22 Enter another number: 14 Enter another number: −99 Data written to numbers.txt

Using Python's for Loop to Read Lines

write a for loop that automatically reads the lines in a file without testing for any special condition that signals the end of the file. When you simply want to read the lines in a file, one after the other. for variable in file_object: ....statement ....statement .....etc.


Related study sets

Match REASONS with EVIDENCE & Counter Claim with Rebuttal

View Set

Chapter 19: Display Technologies

View Set

قراءة-ابو ريحان البيروني

View Set