Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read in one character at a time from a file in python?

I want to read in a list of numbers from a file as chars one char at a time to check what that char is, whether it is a digit, a period, a + or -, an e or E, or some other char...and then perform whatever operation I want based on that. How can I do this using the existing code I already have? This is an example that I have tried, but didn't work. I am new to python. Thanks in advance!

    import sys

    def is_float(n):
        state = 0
        src = ""
        ch = n
        if state == 0:
            if ch.isdigit():
                src += ch
                state = 1
                ...

    f = open("file.data", 'r')
    for n in f:
        sys.stdout.write("%12.8e\n" % is_float(n))
like image 941
Harley Jones Avatar asked Sep 01 '14 19:09

Harley Jones


1 Answers

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)
like image 162
Veky Avatar answered Oct 12 '22 14:10

Veky