Hi,
suppose I am reading lines from a file or stdin.
I want to just "peek" in to the next line, and if it starts
with a special character I want to break out of a for loop,
other wise I want to do readline().
Is there a way to do this?
for example:
while 1:
line=stdin.peek _nextline()
if not line: break
if line[0]=="|":
break:
else:
x=stdin.nextlin e()
# do something with x
thanks 19 10631
les> suppose I am reading lines from a file or stdin. I want to just
les> "peek" in to the next line, and if it starts with a special
les> character I want to break out of a for loop, other wise I want to
les> do readline().
Create a wrapper around the file object:
class PeekFile:
def __init__(self, f):
self.f = f
self.last = None
def push(self, line):
self.last = line
def readline(self):
if self.last is not None:
line = self.last
self.last = None
return line
return self.f.readline ()
def __getattr__(sel f, attr):
return getattr(self.f, attr)
Then use it like so:
stdin = PeekFile(stdin)
while 1:
line = stdin.readline( )
if not line:
break
if line[0] == "|":
stdin.push(line )
break
else:
# do something with line
Of course, this could be tested (which my example hasn't been), PeekFile can
probably can be written as a subclass of the file class, and made more
generally robust (handle filenames as inputs instead of file objects,
support write modes, etc), but this should give you the general idea.
Skip le*******@yahoo .com writes: Hi, suppose I am reading lines from a file or stdin. I want to just "peek" in to the next line, and if it starts with a special character I want to break out of a for loop, other wise I want to do readline().
Is there a way to do this? for example: while 1: line=stdin.peek _nextline() if not line: break if line[0]=="|": break: else: x=stdin.nextlin e() # do something with x
thanks
-- http://mail.python.org/mailman/listinfo/python-list
Well what you can do is read the line regardless into a testing variable.
here is some sample code (writting this off the topof my head so syntax
might be off some)
import re
file = open("test.txt" , 'r')
variablestr = '' #this would be your object.. in my example using a string
for the file data
file.seek(0,2)
eof = file.tell() #what this is the position of the end of the file.
file.seek(0,0)
while file.tell() != eof:
testline = file.readline()
if re.match("#", testline) == True:
break
else:
variablestr += testline
file.close()
now if I was concerned with being at the beging of the testline that it read
in what you can do is in the if is something like:
file.seek((file .tell() - len(testline)), 0)
and that will move you back to the beginging of that line which is where the
readline from the previous call left you before the "peek".
hope that helps some..
Jeff
Jeffrey Maitland writes: le*******@yahoo .com writes:
Hi, suppose I am reading lines from a file or stdin. I want to just "peek" in to the next line, and if it starts with a special character I want to break out of a for loop, other wise I want to do readline().
Is there a way to do this? for example: while 1: line=stdin.peek _nextline() if not line: break if line[0]=="|": break: else: x=stdin.nextlin e() # do something with x
thanks
-- http://mail.python.org/mailman/listinfo/python-list
Well what you can do is read the line regardless into a testing variable.
here is some sample code (writting this off the topof my head so syntax might be off some)
import re
file = open("test.txt" , 'r')
variablestr = '' #this would be your object.. in my example using a string for the file data
file.seek(0,2) eof = file.tell() #what this is the position of the end of the file. file.seek(0,0)
while file.tell() != eof: testline = file.readline() if re.match("#", testline) == True: break else: variablestr += testline
file.close()
now if I was concerned with being at the beging of the testline that it read in what you can do is in the if is something like: file.seek((file .tell() - len(testline)), 0) and that will move you back to the beginging of that line which is where the readline from the previous call left you before the "peek".
hope that helps some..
Jeff -- http://mail.python.org/mailman/listinfo/python-list
I noticed something in my code.
re.match("#", testline) == True isn't possible it would be more like.
re.match("#", testline) != None
Jeffrey Maitland wrote: file.seek(0,2) eof = file.tell() #what this is the position of the end of the file. file.seek(0,0)
while file.tell() != eof:
no no no. that's not how you read all lines in a text file -- in any
programming language.
in recent versions of Python, use:
for testline in file:
to loop over all lines in a given file.
if re.match("#", testline) == True: break
ahem. RE's might be nice, but using them to check if a string
starts with a given string literal is a pretty lousy idea.
if testline[0] == "#":
break
works fine in this case (when you use the for-loop, at least).
if testline might be empty, use startswith() or slicing:
if testline.starts with("#"):
break
if testline[:1] == "#":
break
(if the thing you're looking for is longer than one character, startswith
is always almost the best choice)
if you insist on using a RE, you should use a plain if statement:
if re.match(patter n, testline):
break # break if it matched
</F>
On Tue, 2004-12-14 at 03:09, le*******@yahoo .com wrote: Hi, suppose I am reading lines from a file or stdin. I want to just "peek" in to the next line, and if it starts with a special character I want to break out of a for loop, other wise I want to do readline().
Assuming there's a good reason, such as monster lines, not to just read
the next line anyway, I'd suggest read()ing the next character then
seek()ing back by one character to restore the file position.
def peekChar(fileob j):
ch = fileobj.read(1)
fileobj.seek(-1,1)
return ch
--
Craig Ringer le*******@yahoo .com wrote: Hi, suppose I am reading lines from a file or stdin. I want to just "peek" in to the next line, and if it starts with a special character I want to break out of a for loop, other wise I want to do readline().
Is there a way to do this? for example: while 1: line=stdin.peek _nextline() if not line: break if line[0]=="|": break: else: x=stdin.nextlin e() # do something with x
thanks
The itertools approach:
(some preparations) import itertools file("tmp.txt", "w").write( """\
.... a
.... b
.... c
.... |
.... d
.... e
.... f
.... """)
(1) You are only interested in lines after and including the "special" line:
def predicate(line) :
.... return not line.startswith ("|")
.... for line in itertools.dropw hile(predicate, file("tmp.txt") ):
.... print line,
....
|
d
e
f
(2) You want both the "head" and the "tail", where the tail includes the
"special" line:
lines = iter(file("tmp. txt")) for line in lines:
.... if line.startswith ("|"):
.... lines = itertools.chain ([line], lines)
.... break
.... print "head", line,
....
head a
head b
head c for line in lines:
.... print "tail", line,
....
tail |
tail d
tail e
tail f
Peter
Skip Montanaro wrote: les> suppose I am reading lines from a file or stdin. I want to just les> "peek" in to the next line, and if it starts with a special les> character I want to break out of a for loop, other wise I want to les> do readline().
Create a wrapper around the file object:
[snip] Of course, this could be tested (which my example hasn't been)
If you'd like something that works similarly and has been tested a bit,
try one of my recipes for peeking into an iterator: http://aspn.activestate.com/ASPN/Coo.../Recipe/304373
You also might consider writing an iterator wrapper for a file object: class strangefileiter (object):
.... def __init__(self, file):
.... self.itr = iter(file)
.... def __iter__(self):
.... while True:
.... next = self.itr.next()
.... if not next or next.rstrip('\n ') == "|":
.... break
.... yield next
.... file('temp.txt' , 'w').write("""\
.... some text
.... some more
.... |
.... not really text""") for line in strangefileiter (file('temp.txt ')):
.... print repr(line)
....
'some text\n'
'some more\n' file('temp.txt' , 'w').write("""\
.... some text
.... some more
....
.... really text""") for line in strangefileiter (file('temp.txt ')):
.... print repr(line)
....
'some text\n'
'some more\n'
'\n'
'really text'
Steve
OK, I am sorry , I did not explain my problem completely.
I can easily break from the loop when I see the character in a line
that I just read; however my problem involves putting back the line I
just read since if I have seen this special character, I have read one
line too many. Let me illustrate
suppose the file has 3 lines
line1.line1.lin e1 line2.line2.li ne
line3.line3.lin e3
now suppose I have read the first line already.
then I read the second line and notice
that there is a ">" in front (my special character)
then I want the put back the second line into the
file or the stdin.
An easy way is if i read all the lines in to an array
and then I can put back the line with the special
character back into this array. However,
this file I am readding is huge! and I can read
it all in one swoop (not enough memory).
for x in stdin:
if x[0]==">":
#### put back the x some how... <-----
break
else:
print x
I hope this is clear
thanks le*******@yahoo .com wrote: now suppose I have read the first line already. then I read the second line and notice that there is a ">" in front (my special character) then I want the put back the second line into the file or the stdin.
Amended iterator class example using my peekable recipe: class strangefileiter (object):
.... def __init__(self, file):
.... self.iter = peekable(file)
.... def __iter__(self):
.... while True:
.... next = self.iter.peek( )
.... if not next or next.rstrip('\n ') == "|":
.... break
.... yield self.iter.next( )
.... file('temp.txt' , 'w').write("""\
.... some text
.... some more
.... |
.... not really text""") f = strangefileiter (file('temp.txt ')) for line in f:
.... print repr(line)
....
'some text\n'
'some more\n' remainder = f.iter for line in remainder:
.... print repr(line)
....
'|\n'
'not really text'
Note that because I wrap the file iterator with a peekable[1] object,
the lines aren't consumed when I test them. So to access the remaining
lines, I just use the iter field of the strangefileiter object.
Steve
[1] http://aspn.activestate.com/ASPN/Coo.../Recipe/304373 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: AngleWyrm |
last post by:
I have created a new container class, called the hat.
It provides random selection of user objects, both with and without
replacement, with non-uniform probabilities. Uniform probabilities are a
degenerate case, and can also be stored.
Here's the web-page, with complete source, illustration, and example usage.
Take a look-see, and post your critique!
http://home.comcast.net/~anglewyrm/hat.html
|
by: Tim |
last post by:
I have used a graphic 'next record' button on a form. How can I stop it
from going past the last existing record? In other words, I don't want it
to take the user to a blank record.
Thanks
Tim
|
by: Jeffrey Hiess |
last post by:
Something like getchar() doesn't work, since it "waits" for input.
#include <stdio.h>
while (1)
{
if (getchar()) /* break if any key is pressed */
{
break;
}
|
by: CeyloR |
last post by:
Can anyone tell me what the "c" means in a statement like this:
strTest = New String(" "c,10)
I know the 10 in above example stands for the maxlength of characters
in the string. Is it posible to skip this maxlength?
I'm trying to open a textfile an put it into a string, and therefor I
just want to read the whole textfile til EOF.
|
by: Mark P |
last post by:
I'm implementing an algorithm and the computational flow is a somewhat
deep. That is, fcn A makes many calls to fcn B which makes many calls
to fcn C, and so on. The return value of the outermost fcn is a boolean
and there are certain places within the inner functions where it may
become apparent that the return value is false. In this case I'd like
to halt the computation immediately and return false.
My current approach is to have...
| |
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
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...
|
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...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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...
|
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...
| |
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();...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |