Python : Read Text File Character By Character In Loop
For example, there's a text file which contains numbers from 0 to 9: 0123456789 Using the following function, I'd like to get output like this: >>> print_char('filename'
Solution 1:
I'd approach this differently, and make a function that takes in a filename that returns a generator:
defreader(filename):
withopen(filename) as f:
whileTrue:
# read next character
char = f.read(1)
# if not EOF, then at least 1 character was read, and # this is not emptyif char:
yield char
else:
return
Then you need to give the filename only once
r = reader('filename')
And the file is kept opened for much faster operation. To fetch next character, use the next
built-in function
print(next(r)) # 0print(next(r)) # 1
...
You can also use itertools
, such as islice
on this object slice characters, or use that in a for
loop:
# skip characters until newlinefor c in r:
if r == '\n':
break
Post a Comment for "Python : Read Text File Character By Character In Loop"