繁体   English   中英

如何从python中的文件或列表中查找数据

[英]how do you find data from a file or list in python

我正在尝试从列表/文件中放入的数据确定用户是否超过18岁。

def pulldata()def enterdata() 这是完整的代码。

def enterdata():
    myFile=open("members.txt", "at")
    myList = []
    firstname = input("please enter first name")
    myList.insert(0,firstname)
    lastname = input("please enter last name")
    myList.insert(1,lastname)
    age = int(input("please enter age"))
    myList.insert(2,age)
    print (myList)
    for item in myList:
        myFile.write(str(item))
    myFile.write("\n")
    myFile.close()
    userchoice()
def readfile():
    myFile=open('members.txt', 'r')
    details = myFile.read()
    print(details)
    myFile.close()
    userchoice()
def pulldata():
    myFile = open ("members.txt", "rt")
    myList = []
    for line in myFile:
        line = line.strip("\n")
        myList.append(line)
        print (myList)
    myFile = myList(map(int,age))       
    myFile.close
    userchoice()

任何帮助,将不胜感激。

Traceback (most recent call last): File "D:\\D\\users.py", line 63, in <module> login() File "D:\\D\\users.py", line 10, in login userchoice() File "D:\\D\\users.py", line 24, in userchoice enterdata() File "D:\\D\\users.py", line 42, in enterdata myFile.write(item+" ") TypeError: unsupported operand type(s) for +: 'int' and 'str'

好的,为了简化操作,我将enterdata()文件中的age值更改为myList.insert(2," Age: " + str(age)) 原因是,现在您可以执行一些字符串连接以从文件中获取年龄,如下所示:

myList = []
def enterdata():
    list = []
    firstname = input("please enter first name")
    list.insert(0,firstname)
    lastname = input("please enter last name")
    list.insert(1,lastname)
    age = int(input("please enter age"))
    list.insert(2," Age: " + str(age))
    myList.append(list)
    print (myList)
    userchoice()
def readfile():
    print(myList)
    userchoice()
def pulldata():
    Listof18Yrolds = []
    for id, line in enumerate(myList):
        age = str(line[2])
        age = age[age.rindex(':')+1:].replace(" ","")
        if int(age) >= 18:
            Listof18Yrolds.append(line)
            print(Listof18Yrolds)
    if len(Listof18Yrolds) >= 0:
        print("Users 18 and over..")
        print(Listof18Yrolds)
    else:
        print("Sorry all users are under 18.")
    userchoice()

为了解释这里发生的情况,该行age = str(line[line.rindex(':')+1:]).replace(" ","")将字符age = str(line[line.rindex(':')+1:]).replace(" ","")冒号后面以获取年龄。 然后需要修剪空白。 以便以后可以转换为int。 然后,您可以检查年龄是否在18岁以上,如果是,请添加到列表中。

编辑:我删除了文件内容,并将myList = []从方法中移出

编辑:添加了缺少的子例程def pulldata()

**编辑:**这仅适用于列表。 自删除文件创建以来,我删除了文件的所有实例。 ****

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM