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.
Modify the code above to remove the newline from each line after it is read in.
Checkpoint 8.14.4.
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.
Checkpoint 8.14.7.
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.
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.
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.
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.
def num_chars(filename):
---
count = 0
---
with open(filename) as file:
---
while open(filename) as file: #distractor
---
for line in file:
---
count += len(line)
---
file.close() #distractor
---
return count
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.
def num_chars(filename):
---
count = 0
---
file = open(filename):
---
file = with open(filename): #distractor
---
for line in file:
---
count += len(line)
---
file.close()
---
return count
Checkpoint 8.14.19.
Checkpoint 8.14.20.
Run the code below to see what it prints.
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>