[Tutor] text processing by reading in a character at a time

Magnus Lyckå magnus at thinkware.se
Sun Jul 18 02:05:55 CEST 2004


At 17:51 2004-07-17 -0600, ppareek wrote:
>Hi,
>I was wondering if anyone new an efficient way of reading in a character at a
>time from a file(I want to directly process a character from the file and not
>by reading in lines because I want to be able to access the postion of the
>character in the file)

It typically isn't efficient to read files one character at a time,
but the simple way to do it is with "f.read(1)" (if f is your file
object).

It isn't exactly rocket science to access the position in the file
even if you read more characters at a time. What are you trying to
do? Do you understand how f.seek() and f.tell() works?

For instance, if you want to modify a file, you can open it in
'rb+' mode, read it all into a string s, and do something like
this to replace a certain character with another:

f = open(file_name, 'rb+')
s = f.read()
for pos, char in enumerate(s):
     if char == myTarget:
         f.seek(pos)
         f.write(myValue)


--
Magnus Lycka (It's really Lyckå), magnus at thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language 



More information about the Tutor mailing list