如何从txt文件中删除密钥和密钥值?例如,如果用户想要从此文件中删除名为Sarah的人:
function addpoint(map,x,y,msg,type)
{
var LatLng = new google.maps.LatLng(x,y);
var mi= getMarkerImage(type);
var marker = new google.maps.Marker({position:LatLng,icon:mi,map: map, title: type});
var infowindow = new google.maps.InfoWindow({ content: '' });
if(msg!="")
{
google.maps.event.addListener(marker, 'click', function() {
if(last_infowindow){
last_infowindow.close();
}
infowindow.content = msg;
infowindow.open(map,marker);
last_infowindow = infowindow;
});
}
return LatLng;
}
目前我有以下内容:
Joe,Bloggs,J.bloggs@example.com,01269 512355, 1, 0, 0, 0,
Sarah,Brown,S.brown@example.com,01866 522555, 1, 0, 0, 0,
…
代码已被接受,但它不会更改txt文件。我觉得我必须将更新后的信息写回txt文件,但我不知道该怎么做。
L = open("players.txt","r+")
delete_name1 = raw_input ("Enter the first name of the person you wish to delete: ")
for line in L:
s = line.strip()
string = s.split(",")
if delete_name1 == string[0]:
del string[:8] # Doesn't work
print delete_name1 + " has been deleted."
L.close() # Closes the file to free us usage space.
答案 0 :(得分:3)
如果文件很小,只需重写整个文件即可。对于文本文件和内置函数,这是一种简单的方法:
with open(filename) as input_file:
data = []
for line in input_file:
if not line.startswith("Sarah,Brown"):
data.append(line)
with open(filename, 'w') as output_file:
for d in data:
output_file.write(d + '\n')
答案 1 :(得分:0)
要修改文件,您必须完全覆盖该文件。这是一个简短的例子:
1,Trevor,H
2,Matt,D
使用输入文件运行:
Trevor,H
Matt,D
输出结果为:
required