473,624 Members | 2,258 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 4050
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 ReaderWithPushb ack(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(leng th - 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(lengt h)
self.pushback(d ata)
return data

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

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

Similar topics

699
33834
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 capabilities, unfortunately. I'd like to know if it may be possible to add a powerful macro system to Python, while keeping its amazing syntax, and if it could be possible to add Pythonistic syntax to Lisp or Scheme, while keeping all of the...
0
1569
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) 1.2.0 Released > > Yes, if the .open() is an generator then it must return a sequence of > items > > but only one at a time. If the loop body doesn't keep the result object
30
3432
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 I've also heard there are lots of weird ways to do some things kinda like Perl which is bad for me. Any other ideas?
10
3681
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. Andrew dalke@dalkescientific.com
0
8233
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8675
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8619
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7158
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6108
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5561
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4078
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4173
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1482
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.