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

后端 未结 3 511
逝去的感伤
逝去的感伤 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.

提交回复
热议问题