Harley Jones Harley Jones - 5 months ago 35
Python Question

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))

Answer Source

for x in open() reads lines from a file. Read the entire file in as a block of text, then go through each character of the text:

import sys

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

data = open("file.data", 'r').read()
for n in data: # characters
    sys.stdout.write("%12.8e\n" % is_float(n))