Chael trims
Chael trims

Reputation: 49

python not writing when a space in text

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") 

Input: afile.txt

   Welcome here
Good place  

Expected output:

hi
   Welcome here     
Good place

I need to preserve my indendation also. How can I do that?

Upvotes: 1

Views: 102

Answers (2)

Sravan K Ghantasala
Sravan K Ghantasala

Reputation: 1318

In the line :

a = [x.rstrip() for x in f]

replace rstip with strip and you are good to go ...

Upvotes: 0

Anshul Goyal
Anshul Goyal

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

Related Questions