Why is my generator implementation incorrect in Python?
<p>So basically i am writing a program where i need to take in a file that contains uppercase letters, that may or may not be seperated by white space or new lines, and return a generator over the letters in the file.</p>

<p>For example: </p>

<pre><code>Z FM
TM  CC
</code></pre>

<p>Would return a generator with an output of "Z","F","M","T","M","C","C"</p>

<p>The function should be a generator, so it will only load in letters at a time instead of the entire file.</p>

<p>Anyways, here is what i have so far. ANyone tell me where i went wrong?</p>

<pre><code>def buildGen:
    with open(filename) as sample:
        for word in sample:
           for ch in word:
               yield ch
</code></pre>

<p>your logic here is wrong, as according to my understanding you are trying to read the file and yield all the letters in the file by calling your <code>buildGen</code> function.</p>

<p>As you are using a with statement it will close the file each time and you always end up with the first line only. Another point is you are opening the file as sample and using as dna that itself will throw an error.</p>

<p>you can achieve the same using this</p>

<pre><code>fp = open('sample.txt')
# generator for the data
data_generator = (c for c in fp.read())
for char in data_generator:
    print char


def read_chars(fp):
    for line in fp
</code></pre>

python generator