In the following code, if I use:
for line in fin:
It only executes for 'a'
But if I use:
wordlist = fin.readlines()
for line in wordlist:
Then it executes for a thru z.
But readlines()
reads the whole file at once, which I don't want.
How to avoid this?
def avoids():
alphabet = 'abcdefghijklmnopqrstuvwxyz'
num_words = {}
fin = open('words.txt')
for char in alphabet:
num_words[char] = 0
for line in fin:
not_found = True
word = line.strip()
if word.lower().find(char.lower()) != -1:
num_words[char] += 1
fin.close()
return num_words
foreach line in file: foreach letter in alphabet
(instead of foreach letter in alphabet: foreach line in file... in general I/O should allways be the outter of two loops, becuase I/O is much much much much much slower than memory access. - corlettk