Horst LueckWed Nov 6 00:40:44 PST 2002
Rob, your strip() doesn't work because you apply it after the list has
been created by readlines().
If you (only and always) want to strip the last empty line (or list
element) you could use the slice operator lines = lines[:-1].
As a quick&dirty approach, i.e. w/o argument checking or IOException
checking:
"""
from sys import argv
rawData = open(argv[1]).readlines() # file.close() at gc
strippedData = []
numericData = []
for item in rawData:
if item.strip():
strippedData.append(item) # or strip if desired
numericData.append( int(item) ) # a hint about string -> int
print strippedData # note, if not stripped, trailig \012 is octal (x0A)
print numericData
"""
See also #comment in text below.
Hey Rob -- welcome to python community ! .......... Horst
On Tue, 5 Nov 2002, Rob Hudson wrote:
> Hello,
>
> I'm trying to read in a file that looks like this:
> ====
> 1
> 2
> 3
> 4
>
> ====
>
> Note the empty line last. What I want to do is remove the new line
> characters, filter out the final empty string, and shove all that into a
> list.
>
> Here is my Python code, which doesn't filter the final empty string, though
> I'm not sure why. Any ideas or code improvements most welcome.
>
> Thanks,
> Rob
>
> #!/usr/bin/env python
> import sys
>
> def processFile (filename):
>
> f = open(filename, 'r')
> lines = [line.rstrip() for line in f.readlines()]
> f.close()
>
> filter(None,lines)
>
> return lines
>
> def printStack (stack):
> for item in stack:
> print "(%s)" % item
# if you file.readlines() you get list[string]
# --forget about the ugly %-stuff and use overloaded operator '+'
# for simple output.
# Here just 'print item' , or print 'some text', some_int,
>
>
> if len(sys.argv) == 2:
> stack = processFile(sys.argv[1])
> printStack(stack)
> else:
> print "Must specify input file",
> exit(0)
>
> _______________________________________________
> Think mailing list
> Think at zoneverte.org
> http://mail.zoneverte.org/cgi-bin/listinfo/think
>
_______________________________________________
Think mailing list
Think at zoneverte.org
http://mail.zoneverte.org/cgi-bin/listinfo/think