To start this lab, download this zip file.
Lab 11 - File Read
Activities
num_lines.py
Write a function num_lines(filename)
that returns the number of lines in a file.
twinkle_twinkle.txt
Twinkle, twinkle, little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky
Twinkle, twinkle, little star
How I wonder what you are
For example:
num_lines("twinkle_twinkle.txt")
Would return:
6
num_words_line.py
Write a function num_words_line(line)
that returns the number of words in a line.
For example:
num_words_line("Baa Baa Black Sheep have you any wool?")
Would return:
8
num_words_file.py
Write a function num_words_file(filename)
that returns the number of words in a file.
humpty.txt
Humpty Dumpty sat on the wall
Humpty Dumpty had a great fall
All the king's horses and all the king's men
Couldn't put Humpty together again
For example:
num_words_file("humpty.txt")
Would return:
26
sum_line.py
Write a function sum_line(line)
that returns the sum of all the numbers in a line.
Uses .split()
to get a list of words (in our case, numbers).
For example:
sum_line("1 314 42 3")
Would return:
360
sum_file.py
Write a function sum_file(filename)
that returns the sum of all the numbers in a file.
numbers.txt
1 2 3 4
5 6 7 8
9 10 11 12
For example:
sum_file("numbers.txt")
Would return;
78
most_words.py
Write a function most_words(filename)
that opens a file and returns the line in the file with the largest word count.
If there is a tie, return whichever line comes first.
london_bridge.txt
London Bridge is falling down
Falling down
Falling down
London Bridge is falling down
My Fair Lady.
For example:
most_words("london_bridge.txt")
Would return:
"London Bridge is falling down"
Grading
Activity | Points |
---|---|
num_lines.py | 5 points |
num_words_line.py | 5 points |
num_words_file.py | 5 points |
sum_file.py | 5 points |
sum_line.py | 5 points |
most_words.py | 5 points |