Python,如何检查csv文档上是否重复了行的第一个元素

2024-09-19 23:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python做一个简单的密码管理器,用户需要输入平台、用户和密码

我试图填充csv,以防csv是空的,我还将这两个变量定义为一个列表

在尝试检查输入平台是否已在csv文件中时,我不断收到一个错误

这是代码的一部分:

if n=="1": 
        fo=open(reqfile,'r')
        data=csv.reader(fo)
        datatoread=list(data)
        while check==False:
            newline.append(input("introduce platform:").lower)
            for x in range(len(datatoread)-1):
                if newline[0]==datatoread[x[0]]:
                    print("You already setup an username and password for this platform, please change the platform")
                    
                    check=False
                else:
                    check=True

在append语句之后打印(换行)时的输出:

[<built-in method lower of str object at 0x037AF680>]

这就是我的突破点:

 fo=open(reqfile,'r')
 data=csv.reader(fo)
 datatoread=list(data)
 while check==False:
        newline.append(input("introduce platform:"))
        for x in range(len(datatoread)):
            print(newline)
            print(datatoread)
            if newline[0]==datatoread[x[0]]:
                print("You already setup an username and password for this platform, please change the name of the platform")
                check=False
                newline.pop()
                break
            else:
                check=True
            break

输出为:

['youtube']

[['Platform', 'Username', 'Password']]

也有同样的错误

错误:

File "/PassMan.py", line 27, in if newline[0]==datatoread[x[0]]: TypeError: 'int' object is not subscriptable

如果您需要所有代码,我的github repo: https://github.com/DavidGarciaRicou/PasswordManagerPython


Tags: csvtheinfalsefordataifcheck
2条回答

我建议您使用pandas来读写您的CSV文件。我相信它将帮助您处理这种文件类型

This answer显示如何检查熊猫数据帧(即您的CSV文件)中是否有字符串

谢谢大家的帮助

我用这段代码解决了问题,但仍然不知道我做错了什么:

    while check==False:
        newline.append(input("Introduce platform:"))
            
        for x in range(0,len(datatoread)):
            platcheck=datatoread[x]
            plattochk=platcheck[0]
            if newline[0]==plattochk:
                print("You already setup an username and password for this platform, please change the name of the platform")
                check=False
                newline.pop()
                break
        try:
            if newline[0]!=plattochk:
                check=True
        except:
            pass
    fo.close

相关问题 更多 >