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

时间:2017-10-03 18:49:53

标签: python python-3.x list file

我正在尝试确定用户是否已超过列表/文件中的数据。

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'

1 个答案:

答案 0 :(得分:0)

好的,为了让这更容易,我将进入senddata()文件的年龄值更改为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(" ","")正在拉动冒号后的字符以获取年龄。然后需要修剪空白。以后能够转换为int。然后,您可以检查年龄是否为18岁及以上,如果是,请添加到列表中。

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

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

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