简体   繁体   English

当文本中的空格时python不写

[英]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. 如果下一行中出现“ Welcome”,我将在文本文件中写入“ hi”的工作代码。

But, if the next line begins with whitespace before word 'Welcome' then it doesnot displays 'hi' 但是,如果下一行以单词“ Welcome”之前的空格开头,则不会显示“ 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 输入: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. 您目前正在直接检查“ Welcome使用”。 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] . 我看到您之前在a = [x.rstrip() for x in f]完成了rstrip Do a lstrip instead to remove whitespaces from the left. lstrip删除左侧的空格。 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 ... strip代替rstip ,你就很好...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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