How to read a single character at a time from a file in Python?

后端 未结 12 792
萌比男神i
萌比男神i 2020-11-28 05:49

Can anyone tell me how can I do this?

12条回答
  •  余生分开走
    2020-11-28 06:12

    I learned a new idiom for this today while watching Raymond Hettinger's Transforming Code into Beautiful, Idiomatic Python:

    import functools
    
    with open(filename) as f:
        f_read_ch = functools.partial(f.read, 1)
        for ch in iter(f_read_ch, ''):
            print 'Read a character:', repr(ch) 
    

提交回复
热议问题