我没有在python中编辑具有以下内容的文件的逻辑:
session1: Part1
host1: #All the four host here should be user input
host2:
host3:
host4:
end
session2: Part2 #The UP,DOWN,LEFT,RIGHT values can be jumbled among sides
host1:
up = host2
host2:
down = host3
host3:
left = host4
host4:
right = host3
end
在文件“session1”的第一部分,它应该从主机1到4获得2或3或4个输入作为来自用户的字符串,并且在文件“session2”的第二部分中它必须更新相同的输入因此取代“host1 to 4:”。但是根据用户的不同(上,左,下,右)可以混淆,这意味着他们可以将值向上或向下移动到右或左,但是“host1,2,3,4:”在“ session2“应该保持不变。如果它不可理解,我可以解释一下,我已经写了这个没有写回文件的漏洞代码,有没有办法做得更好?
#!/usr/bin/python
File1 = open ("test","rw+")
Read1 = File1.read()
Spl = Read1.split()
Inp_Host = raw_input("Enter the host input:")
Side_screen = str(raw_input ("up, down, left, right, choose your way:"))
#if Inp_Host == Spl[2] or Spl [3] or Spl [4] or Spl [5]:
# print "The host already exists"
#else:
if Side_screen == "up":
Spl[2] = Spl[9] = Inp_Host
Spl[12] = input ()
elif Side_screen == "down":
Spl[3] = Spl[13] = Inp_Host
Spl[16] = input ()
elif Side_screen == "left":
Spl[4] = Spl[17] = Inp_Host
Spl[20] = input ()
elif Side_screen == "right":
Spl[5] = Spl[21] = Inp_Host
Spl[24] = input ()
Spl.write()
print Spl.read()
我不确定通过拆分编辑文件是否会将文件放回同一个缩进文件中。