while c = f.read(1)

Bengt Richter bokr at oz.net
Fri Aug 19 01:59:38 EDT 2005


On 18 Aug 2005 22:21:53 -0700, "Greg McIntyre" <greg at puyo.cjb.net> wrote:

>I have a Python snippet:
>
>  f = open("blah.txt", "r")
>  while True:
>      c = f.read(1)
>      if c == '': break # EOF
>      # ... work on c
>
>Is some way to make this code more compact and simple? It's a bit
>spaghetti.
>
>This is what I would ideally like:
>
>  f = open("blah.txt", "r")
>  while c = f.read(1):
>      # ... work on c
>
How about (untested):

   for c in iter((lambda f=open('blah.txt', 'r'): f.read(1)), ''):
       # ... work on c

("if c=='': break" functionality courtesy of iter(f, sentinel) form above)

Of course, reading characters one by one is not very efficient, so if the file
is reasonably sized, you might just want to read the whole thing and iterate
through it, something like 

    for c in open('blah.txt').read():
        # ... work on c

>But I get a syntax error.
>
>    while c = f.read(1):
>           ^
>SyntaxError: invalid syntax
>
>And read() doesn't work that way anyway because it returns '' on EOF
>and '' != False. If I try:
>
>  f = open("blah.txt", "r")
>  while (c = f.read(1)) != '':
>      # ... work on c
>
>I get a syntax error also. :(
>
>Is this related to Python's expression vs. statement syntactic
>separation? How can I be write this code more nicely?
>
Yes, it is related as you suspect. I'll leave it to you to make
a chunk-buffering one-liner for huge files that iterates by characters,
if one-liners turn you on. Otherwise it is easy to write a generator that will do it.
Byt the time I post this, someone will probably have done it ;-)


Regards,
Bengt Richter



More information about the Python-list mailing list