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

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

Can anyone tell me how can I do this?

相关标签:
12条回答
  • 2020-11-28 06:06

    Just:

    myfile = open(filename)
    onecaracter = myfile.read(1)
    
    0 讨论(0)
  • 2020-11-28 06:07

    first open a file:

    with open("filename") as fileobj:
        for line in fileobj:  
           for ch in line: 
               print ch
    
    0 讨论(0)
  • 2020-11-28 06:07

    This will also work:

    with open("filename") as fileObj:
        for line in fileObj:  
            for ch in line:
                print(ch)
    

    It goes through every line in the the file and every character in every line.

    0 讨论(0)
  • 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) 
    
    0 讨论(0)
  • 2020-11-28 06:12

    To make a supplement, if you are reading file that contains a line that is vvvvery huge, which might break your memory, you might consider read them into a buffer then yield the each char

    def read_char(inputfile, buffersize=10240):
        with open(inputfile, 'r') as f:
            while True:
                buf = f.read(buffersize)
                if not buf:
                    break
                for char in buf:
                    yield char
            yield '' #handle the scene that the file is empty
    
    if __name__ == "__main__":
        for word in read_char('./very_large_file.txt'):
            process(char)
    
    0 讨论(0)
  • 2020-11-28 06:13
    with open(filename) as f:
      while True:
        c = f.read(1)
        if not c:
          print "End of file"
          break
        print "Read a character:", c
    
    0 讨论(0)
提交回复
热议问题