![](/img/trans.png)
[英]How can I replace first line of a csv with a header using Python?
[英]How can I make Python using csv read the first word in a line rather than the first character?
我一直在这里寻找解决方案,尽管它们似乎满足了我的需求,但最终却没有为我工作。 我不确定为什么。 我将尝试指出问题的根源,并希望您能够指明为什么会有所不同。
因此,我一直在尝试使用Tkinter GUI创建一个简单的用户名和密码登录系统。 我已经尝试过通过将用户名和密码放在外部CSV文件中来完成这项工作,然后让我的程序运行,一旦已经运行我的游戏的两个用户都尝试登录,然后逐行读取我的csv文件(称为“纸牌Game.csv的接受用户”),该文件与该程序位于同一文件夹中,因此不需要其他目录。 我尝试过这样做,以便用户将其用户名和密码放入不同的Tkinter条目中,然后按下其下方的按钮。 然后,程序会检查是否例如line[0] == PlayerOneUsername and line[1] == PlayerOnePassword
,但是,每次我尝试此操作时,它都不会起作用。 (对于任何人,我的分隔符都是',')。
使它打印出正在阅读的内容后,我发现它总是返回该行的第一个字符而不是第一个单词,因此,它始终会不正确。 我一直在寻找答案,而我已经尝试了其中的一些答案,但是每次尝试实施它时,似乎都在发生同样的问题。 (EG line.split()尚未解决我的问题)。
这是行和行[0]相互比较时的输出。 (然后忽略颜色和标题,这些与游戏有关)。
这是您按下按钮时触发的玩家2评估的一部分(与玩家1评估大致相同):
Success["text"] = ""
if not PasswordLoginInputTwo.get() or not UsernameLoginInputTwo.get():
Success["text"] = "One or more of your password/username entries are empty. Please try again."
else:
csvfile = open ("Accepted Users for Card Game.csv", "r")
Csvreader = csv.reader(csvfile, delimiter = ',')
Success["text"] = "Player Two password/username combination has been read."
for line in csvfile:
print(line[0])
if line:
print(line)
print(line[0])
if line.split(None, 1)[0] == UsernameLoginInputTwo.get() and line.split(None, 1)[1] == PasswordLoginInputTwo.get():
PlayerTwoSuccess = True
PlayerTwoUsername = UsernameLoginInputTwo.get()
PlayerTwoColour = line[2]
PlayerTwoAntithesis = line[3]
PlayerTwoVictorSound = "Victory - "+line[4]+".wav"
PlayerTwoAttempts = PlayerTwoAttempts + 1
外部csv文件只是以简单的行格式排列,如下所示:
PlayerOne,Password1,Purple,Yellow,Donkey Kong
PlayerTwo,Password2,Red,Green,Final Fantasy
PlayerThree,Password3,Pink,Purple,Worms
PlayerFour,Password4,Black,White,Team Fortress 2
我知道答案可能很明显,但是我很生气,似乎找不到答案! 顺便说一句,尽管我不打算继续使用它,但我正在使用Python 2.7。 (您可能会说,我是Python的新手,所以请解释任何类似我非常愚蠢的解决方案-尽管您可能已经从我的代码和整体问题中得到了印象,哈哈)。 谢谢!
因此,基本上,重复一遍,我的印象是line [0]应该是我的“行”中的第一个“单词”,在这种情况下例如是“ PlayerOne”。 相反,它给了我第一个字符,在这种情况下为“ P”。 如何解决此问题? 是什么原因造成的? 我怎样才能做到这是第一个单词而不是第一个字符 ? 谢谢!
您正在迭代:
for line in csvfile:
它将返回代表第一行的字符串 。 您需要遍历阅读器对象:
for line in Csvreader:
然后,line将是在定界符上分割的字符串的元组 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.