我无法用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到4:”。但是边(上、左、下、右)可以根据用户的不同而混淆,这意味着它们可以将值上下或下左右移动,但“session2”中的“host1,2,3,4:”应该保持不变。如果不能理解,我可以解释更多,我已经写了这个缺陷代码,这是不是写回文件,有没有办法做得更好?你知道吗
#!/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()
而且我不确定通过拆分来编辑文件是否会将文件放回相同的缩进。你知道吗
你的代码有很多问题。首先,如果您想写入文件“test”以修改其内容,则必须调用
file.write()
,而不是Spl.write()
。另外,我认为文件模式"rw+"
是无效的;要同时打开一个文件进行读写,您只需要"r+"
;有关详细信息,请参见here。此外,打开文件进行读写操作时,除非另有指定,否则通常会将写操作附加到文件的末尾。如果您想从文件中的一个随机点开始覆盖,或者从头开始覆盖,那么您将需要使用file.seek()
,并且您可能还希望查看file.truncate()
。您可以了解有关文件对象方法here的更多信息。你知道吗相关问题 更多 >
编程相关推荐