Reputation: 183
I am trying to write a function that opens a filename, reads the contents of the file, and then prints the contents 3 letters at a time. Here is what I have tried:
def trigram_printer(filename):
open_file = open(filename)
copy = open_file
three_letters = copy.read(4)
for contents in copy:
print(three_letters)
open_file.close
Upvotes: 2
Views: 1081
Reputation: 16711
copy
simply points to open_file
and your printing the letters for the number of lines in copy
:
with open('test.txt') as open_file:
data = open_file.read(3)
while data != '':
print(data) # print 3-gram
data = open_file.read(3)
Just use a continuous loop to test if the file buffer is empty and print the data during the iteration.
Upvotes: 0
Reputation: 6098
There are several things I’d change about this code:
three_letters
variable, which is why it prints the same thing repeatedly. You need to update the value of three_letters
(by reading three more characters from the file) after you print it.open_file
object, when I’d just use it directly..read(4)
, you print the contents 4 letters at a time, not 3.f = open(filename); ...; f.close()
construction, rather than the more conventional with open(filename) as f; ...
.With those thoughts in mind, here’s how I’d write your trigram printer:
def trigram_printer(filename):
"""Prints the contents of <filename>, three characters at a time."""
with open(filename, 'r') as f:
three_letters = f.read(3)
while three_letters:
print(three_letters)
three_letters = f.read(3)
The key part is that every time three_letters
gets printed, this function reads the next three characters from the file. When it runs out of characters, three_letters
will be an empty string and the while loop will stop.
Upvotes: 3