while c = f.read(1)
en.karpachov at ospaz.ru
en.karpachov at ospaz.ru
Fri Aug 19 06:11:13 EDT 2005
On 18 Aug 2005 22:21:53 -0700
Greg McIntyre 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.
import itertools
f = open("blah.txt", "r")
for c in itertools.chain(*f):
print c
# ...
The "f" is iterable itself, yielding a new line from the file every time.
Lines are iterable as well, so the itertools.chain iterates through each
line and yields a character.
--
jk
More information about the Python-list
mailing list