Reputation: 49
I have working code which writes 'hi' in text file if 'Welcome' is present in the next line.
But, if the next line begins with whitespace before word 'Welcome' then it doesnot displays 'hi'
Code:
with open('afile.txt', 'r+') as f:
a = [x.rstrip() for x in f]
index = 0
for item in a:
if item.startswith("Welcome"):
a.insert(index, "hi")
break
index += 1
# Go to start of file and clear it
f.seek(0)
f.truncate()
# Write each line back
for line in a:
f.write(line + "\n")
Welcome here
Good place
hi
Welcome here
Good place
I need to preserve my indendation also. How can I do that?
Upvotes: 1
Views: 102
Reputation: 1318
In the line :
a = [x.rstrip() for x in f]
replace rstip
with strip
and you are good to go ...
Upvotes: 0
Reputation: 76867
You are currently checking for Welcome
directly. Instead, strip your line of whitespaces, and use the following condition instead
if item.strip().startswith("Welcome"):
EDIT
I see you've done rstrip
earlier in a = [x.rstrip() for x in f]
. Do a lstrip
instead to remove whitespaces from the left. However, if you do this, your indentation will not be preserved.
Upvotes: 1