473,508 Members | 2,257 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Does Python support a peek like method for its file objects?



Hello:

Does Python support a peek like method for its file objects?

I'd like to be able to look at the next byte in a disk file before
deciding whether I should read it with, say, the read() method.
Is it possible to do so in Python?

Your answer would be much appreciated.

Thanks.

Avi Kak
Feb 5 '06 #1
5 4035
On Sun, 05 Feb 2006 05:45:24 +0000, Avi Kak wrote:
Hello:

Does Python support a peek like method for its file objects?

I'd like to be able to look at the next byte in a disk file before
deciding whether I should read it with, say, the read() method.
Is it possible to do so in Python?

# WARNING: untested

fp = file("some file on disk", "rb")
b = ""
while 1:
# peek at the next byte
c = fp.read(1)
# decide whether to read it
if c == "?":
# pretend we never read the byte
del c
fp.seek(-1, 1) # but be careful in text mode!
break
# now read the byte "for real"
b = fp.read(1)
if not b:
# we've reached the end of the file
break
fp.close()

I'm not sure exactly why you'd want to do this, but it should be doable,
at least for files that support seeking.

--
Steven.

Feb 5 '06 #2
On Sun, 05 Feb 2006 19:25:21 +1100, Steven D'Aprano wrote:
On Sun, 05 Feb 2006 05:45:24 +0000, Avi Kak wrote:
Hello:

Does Python support a peek like method for its file objects?

I'd like to be able to look at the next byte in a disk file before
deciding whether I should read it with, say, the read() method.
Is it possible to do so in Python?

# WARNING: untested


Yes, and also completely broken. I don't know what I was thinking. Sigh.
Try this (also untested, but not so obviously broken):

fp = file("some file on disk", "r") # should work in text mode
b = ""
while 1:
# peek at the next byte
c = fp.read(1)
# decide whether to read it
if c == "?":
# pretend we never read the byte
fp.seek(-1, 1) # but be careful in text mode!
break
# now read the byte "for real"
b = c
if not b:
# we've reached the end of the file
break
fp.close()
--
Steven.

Feb 5 '06 #3
Avi Kak wrote:
Hello:

Does Python support a peek like method for its file objects?

I'd like to be able to look at the next byte in a disk file before
deciding whether I should read it with, say, the read() method.
Is it possible to do so in Python?

Your answer would be much appreciated.


If it's a seekable file (not a stream input) then you can use
file.tell() to get the current position, then file.read() to read
some data, then file.seek(), giving it the position you got from
file.tell(), to rewind to the same position. This is the safe version;
in the unsafe version you can skip the file.tell() stuff and just use
relative positioning in the file.seek() operation.

If it's a socket, you can use recv() or recvfrom() if you
set the flags argument to MSG_PEEK.

If it's a stream, you're out of luck, and you'll have to buffer the
data
yourself, although you can use select() or poll() to check on
availability of data if that's what you really want.

At least, in theory. I haven't tried any of this in Python yet.

--Blair

Feb 5 '06 #4
Here's a version that should work in text mode as well:

fp = file("some file on disk", "r")
b = ""
while 1:
p = fp.tell()
# peek at the next byte; moves file position only if a byte is read
c = fp.read(1)
# decide whether to read it
if c == "?":
# pretend we never read the byte
fp.seek(p)
break
# now read the byte "for real"
b = c
if not b:
# we've reached the end of the file
break
fp.close()

--Blair

Feb 5 '06 #5
Avi Kak wrote:
Does Python support a peek like method for its file objects?


A short answer is, "No, it does not." Peek was (I believe) put into
Pascal to simplify certain problems; language processing , for example,
is drastically simplified by 1-character look-ahead. Pascal was
designed as a teaching language, and it provided primitives to ease
the work students did, rather than reflect the realities of an
underlying I/O system. Building usable Pascal runtimes was a pain in
the posterior for precisely this reason.

Often you can build simple code to accomplish your task without
implementing a full peek. Peek affects: read, tell, relative seeks,
end-of-file processing, and waits for user interaction. usually you
need nearly none of this. Maybe all you need is a layer around a
reader with a "pushback" function.

class ReaderWithPushback(object):
def __init__(self, somefile):
self._read = somefile.read
self.held = ''
self.sawEOF = False

def read(self, length):
assert length > 0
while len(self.held) < length and not self.sawEOF:
chunk = self._read(length - len(self.held))
if chunk:
self.held += chunk
else:
self.sawEOF = True
if len(self.held) > length:
self.held, result = (self.held[length :],
self.held[: length])
else:
self.held, result = '', self.held
return result

def pushback(self, somestuff):
self.held = somestuff + self.held

def peek(self, length=1):
data = self.read(length)
self.pushback(data)
return data

--Scott David Daniels
sc***********@acm.org
Feb 5 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

699
33326
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro...
0
1563
by: Jon Franz | last post by:
----- Original Message ----- From: "Jon Franz" <jfranz@neurokode.com> To: "Serge Orlov" <sombDELETE@pobox.ru> Sent: Wednesday, November 19, 2003 2:39 PM Subject: Re: Python Database Objects (PDO)...
30
3382
by: Christian Seberino | last post by:
How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? Python's design is godly. I'm wondering if Ruby's is godly too. I've heard it has solid OOP design but then...
10
3660
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. ...
0
7231
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7336
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
7066
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5643
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5059
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4724
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3214
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3198
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
435
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.