Why do I require an "elif" statement here?
Jim
jscrerar at compuserve.com
Fri Aug 4 13:32:11 EDT 2006
Could somebody tell me why I need the "elif char == '\n'" in the
following code?
This is required in order the pick up lines with just spaces in them.
Why doesn't
the "else:" statement pick this up?
OLD_INDENT = 5 # spaces
NEW_INDENT = 4 # spaces
print 'Reindent.py:'
print '\nFrom file %s' % infile
print 'Change %i space indentation to %i space indentation.' % (
OLD_INDENT, NEW_INDENT)
print 'And place revised file into %s' % outfile
whitespace = ' '
n = 0
nline = 0
for line in input.readlines():
nline += 1
# Only look at lines that start with a space.
if line[0] == whitespace:
i = 0
for char in line:
i += 1
if char == whitespace:
pass
elif char == '\n': # Why do I need this for a
blank line with only spaces?
output.write(line)
break
else: # Why doesn't the blank line
get picked up here?
x = line.count(whitespace*OLD_INDENT,0,i)
# Reindent lines that have exactly a multiple of
OLD_INDENT.
if x > 0 and (i-1)%OLD_INDENT == 0:
output.write(whitespace*NEW_INDENT*x+line.lstrip())
n += 1
break
else:
output.write(line)
break
else:
output.write(line)
input.close()
output.close()
print 'Total number of %i lines reindented out of %i lines.' % (n,
nline)
More information about the Python-list
mailing list