简体   繁体   中英

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?

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.

In the line :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM