我正在尝试在 python 中使用 readlines() 创建的字符串中插入多行。我对其进行了很多小时的调试,但我无法找出问题所在。
我有先前定义的 i 个服务器。 “data”是一个字符串,其中包括我的文本文档,我有一个函数“get_line”,它在字符串中搜索关键字“Queue1 Position”并返回该行。在我的示例中,该行是 82。
...
data = cfg.readlines()
...
#Queue
i = int(gwi["Server"][0]) #Number of Servers
line_idx=get_line(data,'Queue1 Position')
for x in range(1,i+1):
if x==1:
data[line_idx] = ('Queue'+str(x)+' Position { 1.500000 '+str(1.100000-x+1)+' 0.000000 m }\n'+'Queue'+str(x)+
' Points { { 1.500 '+str(0.700-x+1)+' 0.000 m } { 2.500 '+str(0.700-x+1)+' 0.000 m } }\n\n')
print(line_idx) #test
else:
line_idx = line_idx + 1
data[line_idx] = ('Queue'+str(x)+' Position { 1.500000 '+str(1.100000-x+1)+' 0.000000 m }\n'+'Queue'+str(x)+
' Points { { 1.500 '+str(0.700-x+1)+' 0.000 m } { 2.500 '+str(0.700-x+1)+' 0.000 m } }\n\n')
print(line_idx) #test
My Document which I edit looks like that at the beginning.
When I run my code the cfg- file looks like that. 'Server1 NextComponent { EntitySink1 }' is cut.
But when I run my code the result should be like that.
是否可以用 for 循环来解决这个问题?也许还有另一种解决方案。
最佳答案
我自己解决了这个问题。
#Queue
i = int(gwi["Server"][0]) #Number of Servers
line_idx=get_line(data,'Queue1 Position')
del data[line_idx+1]
queue_text = ""
for x in range(1,i+1):
if x<i:
queue_text = queue_text+('Queue'+str(x)+' Position { 1.500000 '+str(1.100000-x+1)+' 0.000000 m }\n'+'Queue'+str(x)+
' Points { { 1.500 '+str(0.700-x+1)+' 0.000 m } { 2.500 '+str(0.700-x+1)+' 0.000 m } }\n\n')
else:
queue_text = queue_text+('Queue'+str(x)+' Position { 1.500000 '+str(1.100000-x+1)+' 0.000000 m }\n'+'Queue'+str(x)+
' Points { { 1.500 '+str(0.700-x+1)+' 0.000 m } { 2.500 '+str(0.700-x+1)+' 0.000 m } }\n')
data[line_idx] = queue_text
关于python - 在使用 readlines() 创建的字符串中使用 for 循环插入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50951893/