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

后端 未结 3 502
逝去的感伤
逝去的感伤 2020-12-05 20:49

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 c

相关标签:
3条回答
  • 2020-12-05 21:30

    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.
    0 讨论(0)
  • 2020-12-05 21:42

    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))
    
    0 讨论(0)
  • 2020-12-05 21:53

    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)
    
    0 讨论(0)
提交回复
热议问题