Python仅附加唯一名称而不是重复名称

时间:2014-12-19 15:22:41

标签: python append bots overwrite

所以它是一个名为chatango的在线游戏机器人。 它是一个白名单,显示所有人都可以使用机器人。

代码是:

whitelist = []
f = open("users/"+name+".txt", "r") # read-only
print("[INFO]LOADING WHITELIST-LVL-1...")
soundz("info")
time.sleep(1)
for name in os.listdir(path):
 if len(name.strip()[:-4])>0: whitelist.append(name.strip()[:-4])
f.close()

当我使用

将另外一个人添加到列表中时
 open("users/"+name+".txt", 'w')

当重新加载时,它会在列表中重复

eg 
Before: man1,man2,man3 
[Reloaded] 
After: man1,man2,man3man1,man2,man3,man4

我如何制作

man1,man2,man3,man4 instead of man1,man2,man3man1,man2,man3,man4 

重装后?

请帮忙

2 个答案:

答案 0 :(得分:1)

尝试使用集合(Python 2 | Python 3)。集合不保留项目的顺序,但只包含唯一的项目,因此您不会有重复的条目。

whitelist = set()
f = open("users/"+name+".txt", "r")
print("[INFO]LOADING WHITELIST-LVL-1...")
soundz("info")
time.sleep(1)
for name in os.listdir(path):
    if len(name.strip()[:-4])>0: whitelist.add(name.strip()[:-4])
f.close()

答案 1 :(得分:0)

我会检查白名单中是否存在该项目,只有在那里才会添加:

因此,您希望附加到白名单:

if not name in whitelist:
    whitelist.append(name)