[ALUG] Python question about reading files

Richard Lewis richardlewis at fastmail.co.uk
Tue Nov 6 16:20:05 GMT 2007


At Tue, 6 Nov 2007 15:54:35 +0000,
Chris G wrote:
> 
> Are there any Python people here?
> 
Yes, loads!

> How do I do the equivalent of the C below in Python :-
> 
>     while ( (str = read(file)) != NULL)
>     {
>         do something;
>     }
> 
Err, my C isn't that hot, but how do this do anything other than put
all the contents of the file in str? Or does it read a line at a time
in some non-obvious way?
> 
> I can read the data OK, i.e. I have opened the file and I can
> successfully read from the file with the line:-
> 
>     tagNum = tlvFile.read(3)
> 
> but I don't see how to make that part of a for/while loop that exits
> at the end of the file.  I can't use an iterator because the file is
> read in variable length chunks whose length depends on context.
> 
You should have a look at:

http://docs.python.org/lib/bltin-file-objects.html

If you /really/ want to read in chunks of three bytes, you could do
this:

chunk = tlvFile.read(3)
while chunk != "":
  print chunk
  chunk = tlvFile.read(3)

Otherwise, why not just read lines and use the free iterator:

for line in tlvFile.readlines():
  print line

Cheers,
Richard
-- 
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Richard Lewis - UEA, MUS PG
+44 (0)1603 592453
http://www.richard-lewis.me.uk/
JID: ironchicken at jabber.earth.li
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
+-------------------------------------------------------+
|Please avoid sending me Word or PowerPoint attachments.| 
|http://www.gnu.org/philosophy/no-word-attachments.html |
+-------------------------------------------------------+



More information about the main mailing list