【问题标题】:Searching for only the first value in an array in a csv file仅搜索 csv 文件中数组中的第一个值
【发布时间】:2018-09-19 14:40:21
【问题描述】:

所以我正在创建一个帐户登录系统,它在数据库中搜索用户名(及其相关密码),如果找到,将登录用户。

这是 csv 文件当前的样子

['dom', '输入密码']

这写在一个字段中(在 Excel 电子表格上),并在用户注册时写入文件。但是,当我尝试登录时,程序只会在该字段中输入的内容时登录,当我希望它在输入 dom 时登录。

这是读取 csv 文件以查看是否在文件中找到用户名/密码的代码:

def Get_Details():
    user_namev2=user_name.get().lower() #Make it so entry box goes red if passwords password is incorrect, and red if username is incorrect/not fault
    user_passwordv2=user_password.get().lower()
    with open ('Accounts.csv', 'r') as Account_file:
        reader = csv.reader(Account_file)
        for row in reader:
            for field in row:
                if field == user_namev2:
                    print ("In file")

以下是注册帐户时将用户名和密码写入 csv 文件的方式。

if re.match(user_password2v2, user_passwordv2):
    print("Passwords do match")
    user_info = []
    user_info.append(user_namev2)
    user_info.append(user_passwordv2)
    with open ('Accounts.csv', 'a') as Account_file:
        writer = csv.writer(Account_file)
        writer.writerow([user_info])
        Bottom()

关于如何搜索 csv 文件以便仅搜索字符串的特定部分并与 user_namev2 匹配的任何想法

【问题讨论】:

  • for field in row 搜索行中的每个字段。尝试查看特定列。例如。 if row[0] == user_name: print("password is", row[1]).
  • 虽然它们写在同一行。就像它在 excel 上的同一领域一样。如果我将它添加到数组并搜索数组怎么办?不知道我会怎么做
  • 我想你的意思是他们都在一个column
  • 我尝试使用 row[0]。还是同样的问题。仅在输入 ['dom', 'enter password'] 时才有效(这是电子表格/csv 文件中写入的字段的精确副本。
  • 当你使用row[0]时,你删除了for field in row:,对吧?

标签: python csv


【解决方案1】:

假设 user_namev2dom 列中的任何内容,user_passwordv2enter password 列中的任何内容,我将使用正则表达式来处理 username 的一部分,即 dom 列.

import regex

with open ('Accounts.csv', 'r') as Account_file:
    reader = csv.reader(Account_file)
    for row in reader:
        if re.findall(user_namevv2[0:5],row[0]): #slice a part of the user name 
            print ("In file")

注意:我还选择将每个row 的第一个元素与row[0] 一起使用,因为那是dom 列。

【讨论】:

  • 在csv文件中,没有dom列。只有 ['dom', 'enter password'] (字面意思是这样写的)写在一个空白文件的 excel 电子表格中。我正在寻找其中的第一个字符串(字符串用'分隔)。所以为了进一步解释,' ' 中的第一个值(在这个例子中是 dom)是用户名。第二个是密码(在本例中为“输入密码”)。抱歉,如果这让您感到困惑。
  • 当我尝试输入该示例时,它给了我错误消息“索引错误:列表索引超出范围”
  • 这很令人困惑,但是好的。问:这是excel还是csv文件?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-01
  • 2018-03-24
  • 2012-06-06
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
相关资源
最近更新 更多