with open(filename) as f:
while True:
c = f.read(1)
if not c:
print("End of file")
break
print("Read a character:", c)
Answer from jchl on Stack Overflowwith open(filename) as f:
while True:
c = f.read(1)
if not c:
print("End of file")
break
print("Read a character:", c)
First, open a file:
with open("filename") as fileobj:
for line in fileobj:
for ch in line:
print(ch)
This goes through every line in the file and then every character in that line.
Reading a single character from a file in python? - Stack Overflow
How can I read a single character at a time?
How to read in one character at a time from a file in python? - Stack Overflow
python - How to read a single character from the user? - Stack Overflow
Another option is to use itertools.chain.from_iterable():
import itertools
with open("test.txt") as f:
for c in itertools.chain.from_iterable(f):
print(c)
chain.from_iterable makes an iterable that returns elements from the first iterable in the given iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Normally this is used to flatten out lists of lists, but in this case, it allows you to ignore the lines.
Whether this is really any better than nested loops is another matter (it'll be a little faster, but that's unlikely to matter), but worth mentioning.
This is one way:
with open(filename) as f:
for line in f:
for c in line:
pass
Or what about this?
with open(filename) as f:
for c in f.read():
pass
Here is a technique to make a one-character-at-a-time file iterator:
from functools import partial
with open("file.data") as f:
for char in iter(partial(f.read, 1), ''):
# now do something interesting with the characters
...
- The with-statement opens the file and unconditionally closes it when you're finished.
- The usual way to read one character is
f.read(1). - The partial creates a function of zero arguments by always calling f.read with an argument of 1.
- The two argument form of iter() creates an iterator that loops until you see the empty-string end-of-file marker.
In fact it's much easier. There is a nice utility in itertools, that's often neglected. ;-)
for character in itertools.chain.from_iterable(open('file.data')):
process(character)
Here's a link to the ActiveState Recipes site that says how you can read a single character in Windows, Linux and OSX:
getch()-like unbuffered character reading from stdin on both Windows and Unix
class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
sys.stdin.read(1)
will basically read 1 byte from STDIN.
If you must use the method which does not wait for the \n you can use this code as suggested in previous answer:
class _Getch:
"""Gets a single character from standard input. Does not echo to the screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
(taken from http://code.activestate.com/recipes/134892/)
ยป pip install readchar
Your syntax is a bit off, your assignment inside the while statement is invalid syntax:
f = open('test.dat', 'r')
while True:
ch=f.read(1)
if not ch: break
print ch
This will start the while loop, and break it when there are no characters left to read! Give it a try.
You can use the two form version of iter as an alternative to a while loop:
for ch in iter(lambda: f.read(1), ''):
print ch