list iteration question
David R. Favor
dfavor at austin.ibm.com
Wed Feb 16 15:28:38 EST 2000
In the attached code, would someone point out why the function
chomp4() throws an exception?
Thanks.
-------------- next part --------------
#!/usr/local/bin/python
import sys
def slurp(filename):
"Slurp all the lines of a file into an list"
try:
f = open(filename)
except IOError:
print "IOError: ", sys.exc_value
sys.exit
return f.readlines()
def chomp1(lines):
"remove the end of line markers from list"
i = 0
while i < len(lines):
if lines[i][-1] == '\n':
lines[i] = lines[i][:-1]
i = i + 1
def chop(str):
"remove the end of line marker from string"
if str[-1] == '\n':
str = str[:-1]
return str
def chomp2(lines):
"remove the end of line markers from list"
i = 0
while i < len(lines):
lines[i] = chop(lines[i])
i = i + 1
def chomp3(lines):
"remove the end of line markers from list"
lines = map(chop,lines)
return lines
def chomp4(lines):
"remove the end of line markers from list"
lines = map(string.rstrip,lines)
return lines
if __name__ == '__main__':
for file in sys.argv[1:]:
lines = slurp(file)
if lines:
lines = chomp4(lines)
for line in lines:
print line
More information about the Python-list
mailing list