Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #81697
| Date | 2014-11-28 12:40 -0500 |
|---|---|
| From | Dave Angel <davea@davea.name> |
| Subject | Re: Iterate over text file, discarding some lines via context manager |
| References | <mailman.16405.1417187079.18130.python-list@python.org> <5478ab81$0$2879$426a34cc@news.free.fr> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.16414.1417196454.18130.python-list@python.org> (permalink) |
Please don't start a new thread when responding to an existing topic.
Just reply-List to the message you're responding to, and include some
context from that message.
On 11/28/2014 12:06 PM, ast wrote:
> Hi
>
> Here is a solution with a custom iterator which operate on files.
> I tested it with a small file. Just a remark, there are no empty line
> on a file, there is at least '\n' at the end of each lines but maybe the
> last one. If readline() got an emptyline, then the end of file has been
> reached.
>
>
> class MyFileItr:
> def __init__(self, f):
> self.f = f
> self.line = ""
>
> def __next__(self):
>
> while True:
> self.line = self.f.readline()
>
> if (self.line == ''):
> raise StopIteration
> if not(self.line.startswith('#') or self.line.isspace() or
> self.line == '\n'):
> return self.line
>
> def __iter__(self):
> return self
>
>
> f = open('test.txt', 'r')
>
> for L in MyFileItr(f):
> print(L, end="")
>
Why would you prefer that over a generator function, as given earlier in
the thread? See for example Ned's message. By using 'yield', you get
Python to generate all the class boilerplate for you.
--
DaveA
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Iterate over text file, discarding some lines via context manager "fetchinson ." <fetchinson@googlemail.com> - 2014-11-28 16:04 +0100
Re: Iterate over text file, discarding some lines via context manager "ast" <nomail@invalid.com> - 2014-11-28 18:06 +0100
Re: Iterate over text file, discarding some lines via context manager Dave Angel <davea@davea.name> - 2014-11-28 12:40 -0500
Re: Iterate over text file, discarding some lines via context manager Marko Rauhamaa <marko@pacujo.net> - 2014-11-28 19:55 +0200
Re: Iterate over text file, discarding some lines via context manager Chris Angelico <rosuav@gmail.com> - 2014-11-29 05:02 +1100
Re: Iterate over text file, discarding some lines via context manager Marko Rauhamaa <marko@pacujo.net> - 2014-11-28 20:04 +0200
csiph-web