Skip to main content

Section 1.17 HW9

Main Concepts:
  • A text file is aΒ sequence of lines, where each line is a string ending in the newline character, ’\n’.
  • Syntax and semantics for calling the openfunction to open a text file for reading.
  • Syntax and semantics for some basic file methods: readline,Β readlines, read, close.
  • Coding pattern: How to iterate over the lines of a text file using aΒ forΒ loop.

Exercises Exercises

Exercise Group.

Suppose pet_names.txt is the name of a text file in our current directory, and we successfully opened the file for reading by executing the following statement:
pets = open('pet_names.txt', 'r')
Match the code chunk with the correct description of the result produced by executing the code.
1.
x = pets.readlines()  # NOTICE the 's' on readlines
  • x is a list of strings; each item in x is a line from pet_names.txt.
  • x is a single string containing the entire contents of pet_names.txt.
  • x is the first line of pet_names.txt.
  • x is the number of lines in pet_names.txt
  • x is the number of characters in pet_names.txt, including newline characters
  • x is the number of characters in pet_names.txt, NOT including newline characters
  • x is the last line of pet_names.txt
2.
x = pets.read()
  • x is a list of strings; each item in x is a line from pet_names.txt.
  • x is a single string containing the entire contents of pet_names.txt.
  • x is the first line of pet_names.txt.
  • x is the number of lines in pet_names.txt
  • x is the number of characters in pet_names.txt, including newline characters
  • x is the number of characters in pet_names.txt, NOT including newline characters
  • x is the last line of pet_names.txt
3.
x = pets.readline()
  • x is a list of strings; each item in x is a line from pet_names.txt.
  • x is a single string containing the entire contents of pet_names.txt.
  • x is the first line of pet_names.txt.
  • x is the number of lines in pet_names.txt
  • x is the number of characters in pet_names.txt, including newline characters
  • x is the number of characters in pet_names.txt, NOT including newline characters
  • x is the last line of pet_names.txt
4.
x = len(pets.readlines())  # NOTICE the 's' on readlines
  • x is a list of strings; each item in x is a line from pet_names.txt.
  • x is a single string containing the entire contents of pet_names.txt.
  • x is the first line of pet_names.txt.
  • x is the number of lines in pet_names.txt
  • x is the number of characters in pet_names.txt, including newline characters
  • x is the number of characters in pet_names.txt, NOT including newline characters
  • x is the last line of pet_names.txt
5.
acc = 0
for line in pets:
    acc = acc + len(line)
x = acc
  • x is a list of strings; each item in x is a line from pet_names.txt.
  • x is a single string containing the entire contents of pet_names.txt.
  • x is the first line of pet_names.txt.
  • x is the number of lines in pet_names.txt
  • x is the number of characters in pet_names.txt, including newline characters
  • x is the number of characters in pet_names.txt, NOT including newline characters
  • x is the last line of pet_names.txt
6.
for line in pets:
    print("hello")
x = line
  • x is a list of strings; each item in x is a line from pet_names.txt.
  • x is a single string containing the entire contents of pet_names.txt.
  • x is the first line of pet_names.txt.
  • x is the number of lines in pet_names.txt
  • x is the number of characters in pet_names.txt, including newline characters
  • x is the number of characters in pet_names.txt, NOT including newline characters
  • x is the last line of pet_names.txt

7. Print First Line.

The function print_first_line takes one parameter, fname, the name of a text file. The function should open the file for reading, print the first line from the file, and close the file.
For example:
Test Result
print_first_line("wordlist1.txt")
happy

8. Get Second Line.

The function get_second_line takes one parameter, fname, the name of a text file. The function should open the file for reading, determine the secondline of the file, close the file, and return the second line (a string).
NOTE: You may assume the file will have at least two lines.
For example:
Test Result
get_second_line("cards.txt")
Six of Diamonds

9. File Iteration: Introduction.

A text file is essentially a sequence of lines. Here is a typical coding pattern for processing each line of a file in turn:
  • Open the file for reading.
  • Use a for loop to iterate over the lines of text, executing a block of one or more statements to process each line.
  • Close the file.
  • Finish processing (print, return, etc.) if needed
NOTE: You will need to use this pattern, or some variation of it, to solve the remaining coding problems in this assignment.
As the following for loop iterates through each line of the file, the loop variable (line) represents the current line of the file as a string of characters.
myFile = open("someTextFile.txt", "r")
for line in myFile:
    do something on each iteration
    do a second thing on each iteration
    etc...
myFile.close()
PROBLEM: Read a string from standard input. Then, iterate over a text file called "cards.txt" and, for each line of the file that starts with the string read from standard input, print that line.
TO DO:
  • Add the missing bits of code to complete the partial solution that is provided (replace the _________ s).
  • Follow the coding pattern described above.
NOTE: If there are no lines in the file beginning with the given string, there should be no output.
For example:
Input Result
Ace
Ace of Hearts

Ace of Spades

Ace of Clubs

Ace of Diamonds

10. File First Chars.

The function file_first_chars takes one parameter, fname, the name of a text file, and returnsa string made up of the first character from each line in the file.Β  You may assume there are no blank lines in the file.
Hint: Use a forloop to iterate over the lines of the file and accumulate the string of first characters.
For example:
Test Result
file_first_chars("wordlist1.txt")
hsaem

11. File First Words.

The function first_words takes one parameter, fname, the name of a text file, and returns a list containing the first word from each line of the file. For example, if the file contents are:
apples are red
bananas are yellow
limes are green
then the list ["apples", "bananas", "limes"] should be returned.NOTE: You may assume the file will contain no blank lines.BIG HINT: If lineis a string representing a line of text (inside of a for loop!), then L = line.split() creates a list of the words in the line.
For example:
Test Result
first_words("snakes.txt")
['Cottonmouth', 'Timber', 'Black', 'Tiger', 'Copperhead',
 'Eastern', 'Western', 'Eastern', 'Prairie', 'Mojave']

12. Print Last Line and Count of Lines.

The function print_last_line takes one parameter, fname, the name of a text file. The function should open the file for reading, read the lines of the file until it reaches the end, print out the last line in the file, report the number of lines contained in the file, and close the file.
Hint: Use a forloop to iterate over the lines and accumulate the count.
For example:
Test Result
print_last_line("wordlist1.txt")
maudlin

The file has 5 lines.

13. File Last Words.

The function last_wordstakes one parameter, fname, the name of a text file, and returns a list containing the last word from each line of the file. For example, if the file contents are:
apples are red
bananas are yellow
limes are green
then the list ["red", "yellow", "green"] should be returned.
NOTE: You may assume the file will contain no blank lines.
BIG HINT: If lineis a string representing a line of text (inside a for loop!), then L = line.split() creates a list of the words in the line.
For example:
Test Result
last_words("wordlist1.txt")
['happy', 'sad', 'angsty',
 'euphoric', 'maudlin']

14. Print Line If It Exists.

The function print_line_if_exists takes two parameters, fname(a string, the name of a text file) and line_num (a non-negative integer, supposedly indexing a line in the file).
  • The function should open the file for reading, print the indicatedΒ line from the file, and close the file.
  • However, if line_num is greater than or equal to the number of lines in the file, a warning message should printed instead.
NOTE: line_num begins indexing at 0; line_num = 0 refers to the FIRST line of the file, line_num = 1 refers to the SECOND line, and so on.
For example:
Test Result
print_line_if_exists("cards.txt", 51)
Ace of Diamonds
print_line_if_exists("cards.txt", 52)
Warning! line_num = 52 is not valid
You have attempted of activities on this page.