【问题标题】:How can I make Python using csv read the first word in a line rather than the first character?如何使用 csv 使 Python 读取一行中的第一个单词而不是第一个字符?
【发布时间】:2018-10-07 18:32:56
【问题描述】:

我在这里四处寻找解决方案,尽管它们似乎符合我的需求,但最终却不适合我。我不是特别清楚为什么。我会尝试说明问题是什么,希望您能说明为什么会有所不同。

所以,我一直在尝试使用 Tkinter GUI 制作一个简单的用户名和密码登录系统。我已经尝试通过将用户名和密码放在外部 CSV 文件中来完成这项工作,然后让我的程序在我的游戏已经运行的两个用户都尝试登录后,逐行读取我的 csv 文件(称为“Accepted Users for Card Game.csv”),它与程序位于同一文件夹中,因此不需要进一步的目录。我已经尝试过让用户将他们的用户名和密码放入不同的 Tkinter 条目中,然后按下它下方的按钮。然后程序会检查是否,例如line[0] == PlayerOneUsername and line[1] == PlayerOnePassword,但是每次我尝试这个时,它都不起作用。 (我的分隔符是 ',',任何人都想知道)。

在让它打印出它正在阅读的内容后,我发现它总是返回行的第一个字符而不是第一个单词,所以它当然一直不正确。我已经搜索了一个答案,其中一些我已经在尝试,但是每次我尝试实现它时,似乎都出现了同样的问题。 (EG line.split() 没有解决我的问题)。

This is the output on comparing the line and line[0] next to each other. (Ignore the colours and the title afterwards, those are to do with the game).

这是当您按下按钮时触发的我的玩家二评估的部分(它或多或少与我的玩家一评估相同):

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”。我该如何纠正这个问题?这是什么原因造成的?我怎样才能使它成为第一个 word 而不是第一个 character?谢谢!

【问题讨论】:

    标签: python csv file-handling tkinter-entry


    【解决方案1】:

    你正在迭代:

    for line in csvfile:
    

    这将返回一个代表第一行的字符串。您需要遍历阅读器对象:

    for line in Csvreader:
    

    然后,行将是一个字符串元组在分隔符上分割。

    【讨论】:

      猜你喜欢
      • 2016-01-18
      • 2017-02-26
      • 2019-11-05
      • 1970-01-01
      • 2011-12-18
      • 2016-06-21
      • 1970-01-01
      • 2016-04-15
      • 2022-11-30
      相关资源
      最近更新 更多