Skip to main content

Section 8.14 Group Work: Reading from Files

It is best to use a POGIL approach with the following. In POGIL students work in groups on activities and each member has an assigned role. For more information see https://cspogil.org/Home 1 .

Note 8.14.1.

If you work in a group, have only one member of the group fill in the answers on this page. You will be able to share your answers with the group at the bottom of the page.
Learning Objectives
Students will know and be able to do the following.
Content Objectives:
  • Learn several ways to read data from a file.
  • Learn how to use try and except.
  • Learn how to use with open for opening a file
  • Learn how to write data to a file.
  • Use a dictionary to track counts of items.
Process Objectives:
  • Modify code that reads from files
  • Modify code to handle an exception
  • Fix code that reads from a file

Subsection 8.14.1 Reading from Files

To read from a file, open the file which returns a file object and loop through the lines in a file. Remember to close the file when you are done reading from it!
Hint.
Labrador Retriever
German Shepherd
Golden Retriever
Beagle
Bulldog
Yorkshire Terrier
Boxer
Poodle
Rottweiler
Dachshunds

Checkpoint 8.14.2.

Run the code below to see what it prints.
Notice that when you run this code it adds a blank line after each line. That is because when you read a line from a file the line contains the newline character (\n). When you print a line you add another newline character which prints as a blank line.

Checkpoint 8.14.3.

Q-2: What string method can you use to remove the newline character from the end of a line?
Modify the code above to remove the newline from each line after it is read in.

Checkpoint 8.14.4.

Q-3: What type of thing is file_obj in the code above?
You can also read all the lines from a file at once into a list. One advantage to this is that you can immediately close the file after that. This makes it easier to remember to close the file.

Checkpoint 8.14.5.

Run the code below to see what it prints.

Note 8.14.6.

You can use either open(file,"r") or just open(file) to read from a file.

Checkpoint 8.14.7.

Q-5: What method do you use to close a file that you have opened?

Checkpoint 8.14.8.

Q-6: When would it not be best to read all of the lines in a file into a list at once?
You can also just read some of the lines from a file using the readline method. This can be handy if you just want to see what type of data is in a file, but don't need to see the entire file.

Checkpoint 8.14.9.

Run the code below to see what it prints.
Modify the code above to print 4 lines and run it again.

Checkpoint 8.14.10.

Q-8: What do you think will happen when you try to run the code below?

Checkpoint 8.14.11.

Run the code below to see what it prints.

Note 8.14.12.

If the file that you try to open is not found, you will get an error.

Checkpoint 8.14.13.

Run the code below to see what it prints. When it asks for another file name type in ‘dogs.txt'.
You can use try and except to handle code that can cause exceptions. Put the code that can cause the exception in the try block.

Checkpoint 8.14.14.

Q-11: What keyword do you use to specify code to execute if there is an error when the code in the body of the try executes?
You can also use with open(file) as name which will automatically close the file after the code block ends. It is particularly important to close the file when you write data to a file.

Checkpoint 8.14.15.

Run the code below to see what it prints.

Note 8.14.16.

When you use with open(file) as name: the file is closed automatically when you leave the block (indented area).

Checkpoint 8.14.17.

Create a function, num_chars(filename), that returns the number of total characters (including new lines) in the file with the passed file name. Initialize a count then open the file and loop through all of the lines in the file and add the length of each line to the count. Close the file. Then return the count. There are extra blocks that are not needed in the solution.

Checkpoint 8.14.18.

Create a function, num_chars(filename), that returns the number of total characters (including new lines) in the file with the passed file name. Initialize a count then open the file and loop through all of the lines in the file and add the length of each line to the count. Close the file. Then return the count. There is an extra block that is not needed in the solution.

Checkpoint 8.14.19.

Q-15: What type of thing is returned from the function below?

Checkpoint 8.14.20.

Run the code below to see what it prints.

Note 8.14.21.

Notice how the code above handles the case when the key isn't yet in the dictionary. The get(key, alternative) method on a dictionary will return the value for the key if it is in the dictionary, otherwise it return return the alternative.
If you worked in a group, you can copy the answers from this page to the other group members. Select the group members below and click the button to share the answers.
<div class="runestone sqcontainer %(optclass)s"> <div data-component="groupsub" id=read_files_groupsub data-size_limit=3> <div class="col-sm-6"> <select id="assignment_group" multiple class="assignment_partner_select" style="width: 100%"> </select> </div> <div id="groupsub_button" class="col-sm-6"> </div> <p>The Submit Group button will submit the answer for each each question on this page for each member of your group. It also logs you as the official group submitter.</p> </div> </div>
https://cspogil.org/Home