![](/img/trans.png)
[英]How do I make a space between words when writing to a text file in python
[英]python not writing when a space in text
如果下一行中出现“ Welcome”,我将在文本文件中写入“ hi”的工作代码。
但是,如果下一行以单词“ Welcome”之前的空格开头,则不会显示“ hi”
码:
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
我也需要保留自己的意愿。 我怎样才能做到这一点?
您目前正在直接检查“ Welcome
使用”。 取而代之的是,剥去空白行,并使用以下条件
if item.strip().startswith("Welcome"):
编辑
我看到您之前在a = [x.rstrip() for x in f]
完成了rstrip
。 lstrip
删除左侧的空格。 但是,如果执行此操作,则缩进将不会保留。
在行中:
a = [x.rstrip() for x in f]
用strip
代替rstip
,你就很好...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.