read in a list in a file to list

Rick Johnson rantingrickjohnson at
Tue Apr 11 22:33:15 EDT 2017

On Sunday, April 9, 2017 at 4:22:59 PM UTC-5, john polo wrote:
> On 4/8/2017 3:21 PM, breamoreboy at wrote:
> > On Saturday, April 8, 2017 at 7:32:52 PM UTC+1, john polo wrote:

> > I'll start you off.
> >
> > with open("apefile.txt") as apefile:
> >      for line in apefile:
> >          doSomething(line)
> >
> > String methods and/or the csv module might be used here in
> > doSomething(line), but I'll leave that to you so that you
> > can learn.  If you get stuck please ask again, we don't
> > bite :)

> Mark, Thanks for the reply. I looked back through the
> methods for strings. I also looked at the csv module, but I
> couldn't tell which one of those would help.

Well, if you plan to write much code in Python you'd be wise
to memorize every string method ASAP. And if you cannot, or
are not willing to do that, then your programming adventures
are going to be very painful. My advice would be to forget
about the csv module for now, and do some major studying of
all the string methods. And please, use the interactive
interpreter to play around with each one of these methods.
Here is a sample of me playing...


    >>> myStr = 'Rick is awesome!'

    >>> type(myStr)
    <type 'str'>

    >>> len(myStr)

    >>> dir(myStr)
    ['__add__', '__class__', '__contains__', '__delattr__',
    '__doc__', '__eq__', '__format__', '__ge__',
    '__getattribute__', '__getitem__', '__getnewargs__',
    '__getslice__', '__gt__', '__hash__', '__init__', '__le__',
    '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
    '__new__', '__reduce__', '__reduce_ex__', '__repr__',
    '__rmod__', '__rmul__', '__setattr__', '__sizeof__',
    '__str__', '__subclasshook__',
    '_formatter_field_name_split', '_formatter_parser',
    'capitalize', 'center', 'count', 'decode', 'encode',
    'endswith', 'expandtabs', 'find', 'format', 'index',
    'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
    'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
    'partition', 'replace', 'rfind', 'rindex', 'rjust',
    'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
    'startswith', 'strip', 'swapcase', 'title', 'translate',
    'upper', 'zfill']

    >>> help(myStr.split)
    Help on built-in function split:

        S.split([sep [,maxsplit]]) -> list of strings

        Return a list of the words in the string S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are removed
        from the result.
    ## END INTERACTIVE SESSION (Python2.x) ##

> The small .txt file does have commas, but with the weird
> form of listname = [1] , [2], [3], etc. for a .csv, I don't
> know how that would be read in a like a .csv. But now that
> I think about it, datObj2 in my script prints just the list
> elements, so maybe the 'listname=' part wouldn't affect
> it...

Again, forget about the csv module for now, it will only
confuse you. Focus on learning Python String methods first.
I can assure you, you might could get by without knowing
jack about the csv module, but you won't get anywhere until
you become intimately familiar with Python String methods.

> Anyway, after reviewing string methods some more, I came up
> with this. If I understood your hint, the loop was supposed
> to somehow break up the long string that came from the
> apelist file,

Mark's code sample iterates over the lines of a file and
passes each line to a function named "doSomething". His hope
was that you would replace the call to doSomething with code
that actually, well, does something.

> but it seemed that trying to use the split method in a loop
> wouldn't work,

Where's your code proving it "would not work"? I can assure
you, a string can be split inside a loop.

> especially since one of my attempts started a list and then
> the interpreter said there were no split methods for list.

Of course, because there is no split method for a list.
Don't believe me? Okay, let's conduct an experiment...


    >>> aList = [1,2,3]
    >>> 'split' in dir(aList)

    ## END INTERACTIVE SESSION (Python2.x) ##

> The new attempt gives me a list, now I have to figure out
> how to deal with unwanted quotation marks and spaces.

Then stop trying to solve 10 problems at once and open your
interactive Python interpreter and do some testing until
your confident that you can remove unwanted chars from a

> Can you make two replacements in the same statement, for
> example ''"','').replace('"','')?

i dunno, did you try testing the code yourself in an
interactive session like i asked? Here, once more...

    >>> myStr
    'Rick is awesome!'
    >>> myStr.replace('Rick', "Rick's patience").replace('awesome', 'wearing thin')
    "Rick's patience is wearing thin!"
    >>> myStr
    'Rick is awesome!'
    ## END INTERACTIVE SESSION (Python2.x) ##

> Per reply of Rick Johnson, I altered variable names to
> something generic.

Indeed you did, and it seems you took my advice to the
extreme, and now your code is a real pain to read. And after
observing that the multiple exchanges here are not producing
the desired result, i am getting the feeling that you are
unwilling to invest the effort required to solve this
problem. Feel free to prove me wrong.

Many people have offered good advice, but you are not
following the advice as closely as you should. So one last
time, i will try to help you by compiling all the tips:

(1) The first step to solving any programming problem is to
devise a "general plan of attack". One of the most common
techniques is called "Divide And Conquer". Using this
technique, you will divide a large problem into many small
problems, solve each of the small problems _individually_,
and then combine them to produce a solution. This type of
"general approach" is what Mark's code example was hinting
at, but i would go further. Follows is a general outline of
how to solve this problem using the necessary amount of

    def handle_result(result):
        # Currently this only prints the parsed line, but once you
        # get everything else working correctly, you can have it
        # do something more interesting.
        print result

    def parse_line(line):
        # Parse out the relevant bits here and return them as a string
        # or list or whatever you want. Currently all this function
        # does is send the `line` back unchanged.
        parsedBits = line
        return parsedBits

    def parse_file(filePath):
        with open(filePath) as fileObj:
            for line in fileObj:
                result = parse_line(line)


(2) Use the interactive nature of Python to test code
snippits as you write the code.

(3) If you are designer of this "ape file format", then for
Guido's sake man, redesign it! It's not a wise way to store
data. Unless you're storing source code. But being that
you're not familiar with strings methods, i have a hard time
believing that this code is part of a mini language.

(4) And while you could "technically" use ast.literal_eval
to solve this problem, i wouldn't suggest it. i think Chris
was just using esoteric comedy on you. And don't worry if
you don't understand why that's funny, it's a joke that is
meant for _us_. You'll understand at some point in the

More information about the Python-list mailing list