How does one detect the EOF gracefully? Assuming I have a pickle file
containing an unknown number of objects, how can I read (i.e.,
pickle.load()) until the EOF is encountered without generating an EOF
exception?
Thanks for any assistance.
MickeyBob
Jul 18 '05
20 14936 lines = iter("abc") first = lines.next() print first a for line in lines:
... print line ... b c
Would hurt less feeling I presume.
Unless it was empty, then you'd get the dreaded StopIteration!
IMO, unconditionally breaking out of a for loop is the nicer way of
handling things in this case, no exceptions to catch.
- Josiah
In article <ma************ *************** ***********@pyt hon.org>,
Egbert Bouwman <eg*********@hc cnet.nl> wrote: A file is too large to fit into memory. The first line must receive a special treatment, because it contains information about how to handle the rest of the file.
Of course it is not difficult to test if you are reading the first line or another one, but it hurts my feelings to do a test which by definition succeeds at the first record, and never afterwards. Any suggestions ?
f = file("lines.txt ", "rt")
first_line_proc essing (f.readline())
for line in f:
line_processing (line)
ought to work.
Regards. Mel.
Peter Otten <__*******@web. de> wrote:
... Looking at it from another angle, the initial for-loop ist just a peculiar way to deal with an empty iterable. So the best (i. e. clear, robust and general) approach is probably
items = iter(...) try: first = items.next() except StopIteration: # deal with empty iterator, e. g.: raise ValueError("nee d at least one item") else: # process remaining data
I think it can't be optimal, as coded, because it's more nested than it
needs to be (and "flat is better than nested"): since the exception
handler doesn't fall through, I would omit the try statement's else
clause and outdent the "process remaining data" part. The else clause
would be needed if the except clause could fall through, though.
Alex
Josiah Carlson <jcarlson <at> uci.edu> writes: IMO, unconditionally breaking out of a for loop is the nicer way of handling things in this case, no exceptions to catch.
There's still a NameError to catch if you haven't initialized line: for line in []:
.... break
.... line
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'line' is not defined
I don't much like the break out of a for loop, because it feels like a misuse
of a construct designed for iteration... But take your pick: StopIteration or
NameError. =)
Steve
Steven Bethard wrote: There's still a NameError to catch if you haven't initialized line:
for line in []: ... break ... line Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'line' is not defined
No, you would put code specific to the first line into the loop before the
break.
I don't much like the break out of a for loop, because it feels like a misuse
I can understand that.
Peter
Alex Martelli wrote: Peter Otten <__*******@web. de> wrote: ... Looking at it from another angle, the initial for-loop ist just a peculiar way to deal with an empty iterable. So the best (i. e. clear, robust and general) approach is probably
items = iter(...) try: first = items.next() except StopIteration: # deal with empty iterator, e. g.: raise ValueError("nee d at least one item") else: # process remaining data
I think it can't be optimal, as coded, because it's more nested than it needs to be (and "flat is better than nested"): since the exception handler doesn't fall through, I would omit the try statement's else clause and outdent the "process remaining data" part. The else clause would be needed if the except clause could fall through, though.
I relied more on the two letters 'e. g.' than I should have as there are two
different aspects I wanted to convey:
1. Don't let the StopIteration propagate:
items = iter(...)
try:
first = items.next()
except StopIteration:
raise MeaningfulExcep tion("clear indication of what caused the error")
2. General structure when handling the first item specially:
items = iter(...)
try:
first = items.next()
except StopIteration:
# handle error
else:
# a. code relying on 'first'
# b. code independent of 'first' or relying on the error handler
# defining a proper default.
where both (a) and (b) are optional.
As we have now two variants, I have to drop the claim to generality.
Regarding the Zen incantation, "flat is better than nested", I tend measure
nesting as max(indent level) rather than avg(), i. e. following my (perhaps
odd) notion the else clause would affect nesting only if it contained an
additional if, for, etc. Therefore I have no qualms to sometimes use else
where it doesn't affect control flow:
def whosAfraidOf(co lor):
if color == red:
return peopleAfraidOfR ed
else:
# if it ain't red it must be yellow - nobody's afraid of blue
return peopleAfraidOfY ellow
as opposed to
def whosAfraidOf(co lor):
if color == red:
return peopleAfraidOfR ed
return peopleAfraidOfA nyOtherColor
That said, usually my programs have bigger problems than the above subtlety.
Peter
On Fri, Oct 08, 2004 at 11:59:32AM +0200, Alex Martelli wrote: option 3, a bit cutesy:
for first_line in thefile: break for line in thefile: ...
(again, in 2.2 you'll need some foo=iter(thefil e)).
This technique depends in the file being positioned at line 2,
after the break.
However, In the Nutshell book, page 191, you write: Interrupting such a loop prematurely (e.g. with break) leaves the file's current position with an arbitrary value.
So the information about the current position is useless.
Do I discover a contradiction ?
egbert
--
Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991
=============== =============== =============== =============== ============
Egbert Bouwman <eg*********@hc cnet.nl> wrote: On Fri, Oct 08, 2004 at 11:59:32AM +0200, Alex Martelli wrote: option 3, a bit cutesy:
for first_line in thefile: break for line in thefile: ...
(again, in 2.2 you'll need some foo=iter(thefil e)). This technique depends in the file being positioned at line 2, after the break.
Not exactly, if by "being positioned" you mean what's normally meant for
file objects (what will thefile.tell() respond, what next five bytes
will thefile.read(5) read, and so on). All it depends on is the
_iterator_ on the file being "positioned " in the sense in which
iterators are positioned (what item will come if you call next on the
iterator).
In 2.3 a file is-an iterator; in 2.2 you need to explicitly get an
iterator as indicated in the parenthesis you've also quoted.
However, In the Nutshell book, page 191, you write: Interrupting such a loop prematurely (e.g. with break) leaves the file's current position with an arbitrary value.
So the information about the current position is useless.
Do I discover a contradiction ?
Nope -- the file's current position is (e.g.) what tell will respond if
you call it, and that IS arbitrary. In 2.2 (which is what the Nutshell
covers) you need to explicitly get an iterator to do anything else; in
2.3 you can rely on the fact that a file is its own iterator to make
your code simpler. But the iteration state is not connected with the
file's current position.
Alex
On Sun, Oct 10, 2004 at 12:41:37AM +0200, Alex Martelli wrote: .... But the iteration state is not connected with the file's current position.
That is very useful information.Tha nks.
egbert
--
Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991
=============== =============== =============== =============== ============
Steven Bethard <st************ @gmail.com> wrote:
... I don't much like the break out of a for loop, because it feels like a misuse of a construct designed for iteration... But take your pick: StopIteration or NameError. =)
Jacopini and Bohm have much to answer for...;-)
Alex This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Jacob H |
last post by:
Hello all,
I'm nearing the completion of my first graphical console game and my
thoughts have turned to the subject of gracefully handling runtime
errors. During development I like to not handle exceptions, so that
program execution will halt and I can immediately read the traceback
to see what's up. Once the bugs are more or less worked out, I have a
system ready wherein any exceptions are caught and an attempt is made
to write the...
|
by: Fotios |
last post by:
Hi guys,
I have put together a flexible client-side user agent detector (written in
js). I thought that some of you may find it useful. Code is here:
http://fotios.cc/software/ua_detect.htm
The detector requires javascript 1.0 to work. This translates to netscape
2.0 and IE 3.0 (although maybe IE 2.0 also works with it)
|
by: Gustav Medler |
last post by:
Hello,
there is a known problem with Opera and the execution of content shown
in <NOSCRIPT> tag.
Everythings works fine, if there is only one simple script like:
http://www.dr-wald.de/test/Opera-NOSCRIPT.html
Switching off Javascript will show the alternative content. Javascript
enabled will only show the JS-content, _not_ the <NOSCRIPT> content.
|
by: R. Smits |
last post by:
I've have got this script, the only thing I want to be changed is the first
part. It has to detect IE version 6 instead of just "Microsoft Internet
Explorer". Can somebody help me out?
I tried "Microsoft Internet Explorer 6" but that doesn't work.
<SCRIPT LANGUAGE="Javascript">
<!--
bName = navigator.appName;
if (bName =="Microsoft Internet Explorer") {
document.write('<link media="screen" rel="STYLESHEET" type="text/css"
|
by: mosaic |
last post by:
Hi, all
I really interested in how to check the memory leak of a program.
Your smart guys, do you have excellent ideas that could share with me?
Thank you.
The following is my idea:
In C programming language, there's a "malloc", there must a "free",
my solution of the detection of leak is, find the corresponding "free"
of "malloc". This the first condition.
| |
by: csgonan |
last post by:
I have a new 64 bit apache 2.2.4 server on Solaris 10 with openssl 0.9.8e. When I DO NOT have the ssl.conf file included and I "apachectl graceful" to apache, all my processes that are gracefully shutdown are shown by a dash (-). When I have the Include line for the ssl.conf file uncommented, the number of Gs never changes, like it is locked in the graceful shutdown.
I have prefork compiled in but not worker or event if that makes a...
|
by: darrenhello |
last post by:
hi there,
I am doing my last year's project and I have a 'little' problem. I have to do an edge detection filter. for now, some normal edge detection filters that I used worked fine but there a problem. I need an edge detection filter in which I can offset the edge according to a variable that the user gives. The problem is that I got no idea of how to make an edge detection filter with an offset.
anyone can help please?
thank you
|
by: origami.takarana |
last post by:
Intrusion Detection Strategies
-----------------------------------
Until now, we’ve primarily discussed monitoring in how it relates to
intrusion detection, but there’s more to an overall intrusion
detection installation than monitoring alone. Monitoring can help you
spot problems in your network, as well as identify performance
problems, but watching every second of traffic that passes through
your network, manually searching for...
|
by: Conrad Lender |
last post by:
In a recent thread in this group, I said that in some cases object
detection and feature tests weren't sufficient in the development of
cross-browser applications, and that there were situations where you
could improve the application by detecting the browser vendor/version.
Some of the posters here disagreed. Since then, I've had to deal with a
few of these cases; some of them could be rewritten to use object
detection, and some couldn't....
|
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...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
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: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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: 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...
| |