Newbie Question

Christian Tismer tismer at tismer.com
Thu Apr 27 15:46:48 EDT 2000


Arnaldo Riquelme wrote:
> 
> Suppose I have a file name tick.tkr that looks like this
> 
> SUNW.
> MFST.
> FOO.
> SPAM.
> MOO.
> End_Of_File
> 
> I want to read the file into a list
> 
> myfile = open("tick.tkr", "r")
> mylist = myfile.readlines()
> 
> Now I have mylist with the contents of tick.tkr. "mylist" looks like this
> ['SUNW.\012', 'MSFT.\012', ..........'End_of_File/012']

Sure? :-)

> How do I read the file into a list without getting the newline character, so
> I can accomplish this
> 
> for tic in mylist:
>     #create file tic.prn
> 
> I know the other P language has something like 'chop' or something like
> that, but I'm not going there.

If you don't care about leading and trailing whitespicy,
you would be lazy and just do this:

import string
mylist = open("tick.tkr").readlines()
mylist = map(string.split, mylist)

If you just want to loose trailing crap, use string.rstrip .

But if you want to be sure only to loose \n, and also might
want to solve the problem that the list line might have no \n,
you are better off with a loop, like so: (after reading)

for i in range(len(mylist)):
    if mylist[i][-1:] == "\n":
        mylist = mylist[:-1]

Finally, here is what I use when I want to have all the lines,
ignoring line ends, but dropping empty lines:

import string
txt = open("tick.tkr").read()  # slurp it all
mylist = string.split(txt, "\n")
# this splits at line ends and removes them,
# but you get probably an empty entry at the end.
mylist = filter(None, mylist) # remove all empty lines.

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaunstr. 26                  :    *Starship* http://starship.python.net
14163 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     where do you want to jump today?   http://www.stackless.com




More information about the Python-list mailing list