How to read a single character at a time from a fi

2019-01-08 12:30发布

Can anyone tell me how can I do this?

12条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-08 12:30
f = open('hi.txt', 'w')
f.write('0123456789abcdef')
f.close()
f = open('hej.txt', 'r')
f.seek(12)
print f.read(1) # This will read just "c"
查看更多
倾城 Initia
3楼-- · 2019-01-08 12:32

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) 
查看更多
该账号已被封号
4楼-- · 2019-01-08 12:36
#reading out the file at once in a list and then printing one-by-one
f=open('file.txt')
for i in list(f.read()):
    print(i)
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-08 12:41

Python itself can help you with this, in interactive mode:

>>> help(file.read)
Help on method_descriptor:

read(...)
    read([size]) -> read at most size bytes, returned as a string.

    If the size argument is negative or omitted, read until EOF is reached.
    Notice that when in non-blocking mode, less data than what was requested
    may be returned, even if no size parameter was given.
查看更多
【Aperson】
6楼-- · 2019-01-08 12:44

first open a file:

with open("filename") as fileobj:
    for line in fileobj:  
       for ch in line: 
           print ch
查看更多
做个烂人
7楼-- · 2019-01-08 12:47
with open(filename) as f:
  while True:
    c = f.read(1)
    if not c:
      print "End of file"
      break
    print "Read a character:", c
查看更多
登录 后发表回答