adding items from a text file to a list

Delaney, Timothy tdelaney at avaya.com
Tue Oct 30 19:24:29 EST 2001


> From: toflatpy2 at oaktown.org [mailto:toflatpy2 at oaktown.org]
> 
> I have a text file with a list of data items.
> 
> ex:
> 
> pickle	(fruit or veggie?)
> pickled eggs	(just plain strange)
> seinfeld	(funny show)
> yada yada	(yada)
> 
> What I want to do is add each item in the file to a python list. The
> thing that is eluding me is how to leave out the comments. I need it
> to scan in the item, skip anything in parenthsis then proceed to the
> next line.

You will need to read the spec carefully. Does it state that anything on a
line following an open parenthesis is part of the comment, or is it only
things within parentheses? These have two different solutions.

1. Everything after the start of a comment is part of the comment (or
guaranteed that there is nothing on a line after a comment).

Find the start of the comment, then discard anything on the line from that
point on. POssibly trim any excess whitespace from the line.

2. Only things within the comment delimiters are comments.

Find the start of a comment, then the end of that comment. Add everything
before the comment to everything behind the comment. Repeat until no
comments are found in the line. Possibly need to remove excess whitespace.

The implementation is up to you. Probably the simplest option would be to
use string.find(), followed by slicing the string at the appropriate points.

Tim Delaney




More information about the Python-list mailing list