Reputation: 13515
I am copying this answer like this
for line in fileinput.input(['my_file'], inplace=True):
sys.stdout.write('_____ {l}'.format(l=line))
to add four underlines to beginning of line. This turns my_file
into a checklist. But the above code prints the underlines on the blank lines too. I want to change the blank lines to full length lines. How do I do that? So if the original lines are like this
abc
def
ghi
the checklist will look like
___ abc
_________________________________________________
___ def
_________________________________________________
___ ghi
_________________________________________________
Thanks!
Upvotes: 0
Views: 197
Reputation: 129019
Strip the whitespace on the line and see if it's non-empty (and thus, truthy). If it's non-empty, do what it did before. Otherwise, it's empty; print the horizontal line. (although I must say 49 characters is somewhat odd)
term_width = 50
with contextlib.closing(fileinput.input(['my_file'], inplace=True)) as f:
for line in f:
if line.strip():
sys.stdout.write('_____ {l}'.format(l=line))
else:
sys.stdout.write('\n'.rjust(term_width, '_'))
Upvotes: 2