Python 如何将文本文件中的行号指定给变量?

Python 如何将文本文件中的行号指定给变量?,python,Python,我试图打印变量“Number”,但它出现了一个错误 'TypeError:列表索引必须是整数,而不是元组' 我不明白?什么是元组?如何解决此问题? 如何将文本文件中的行号指定给变量 def CheckDatabase(): print ("====Check Database===== \nA)Would you like to check details? \nB)Check if they are a member?") TC = input(": ") if TC

我试图打印变量“Number”,但它出现了一个错误

'TypeError:列表索引必须是整数,而不是元组'

我不明白?什么是元组?如何解决此问题? 如何将文本文件中的行号指定给变量

def CheckDatabase():
    print ("====Check Database===== \nA)Would you like to check details? \nB)Check if they are a member?")
    TC = input(": ")
    if TC == "A" or TC == "a":
        NameDetail = input ("Please enter the name you would like to check the details of.\nThis will only work if they are a member\n: ")
        with open('Name.txt') as ND:
            for number, line in enumerate(ND, 1):
                if (str(NameDetail)) in line:
                    Number = number, line in enumerate(ND, 1)
                    print ("\nName = ", NameDetail)

                    A = open("Address.txt", "r")
                    AData =[line.rstrip() for line in A.readlines()]
                    print ("Address = ",(AData[Number]))

                    HN = open("Home Number.txt", "r")
                    HNData =[line.rstrip() for line in HN.readlines()]
                    print ("Home Number = ",(HNData[Number]))

                    MN = open("Mobile Number.txt", "r")
                    MNData =[line.rstrip() for line in MN.readlines()]
                    print ("Mobile Number = ",(MNData[Number]))

                    EAS = open("Email Address.txt", "r")
                    EAData =[line.rstrip() for line in EAS.readlines()]
                    print ("Email Address = ",(EAData[Number]))

                    MDND = open("Email Address.txt", "r")
                    MDNData =[line.rstrip() for line in MDND.readlines()]
                    print ("Medical/Dietry Needs = ",(MDNData[Number]))


                else:
                    print ("Person not found!")
编辑:

import time

def AddToDatabase():
    print ("\nYou are adding to the Database. \nA)Continue \nB)Go Back")
    ATD = input(": ")
    if ATD == "A" or ATD == "a":

        Name = input("\nEnter Name of Member [First Name and Surname]: ")
        with open("Name.txt", "a") as N:
            N.write("\n{}".format(Name))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        print ("\nEnter Address of "+Name+" all on one line")
        print ("In format [Include Commas]")
        print ("\nRoad name with house number [e.g. 1 Morgan Way], Borough [e.g Harrow], City [e.g London], Postcode [e.g. HA5 2EF]")
        Address = input("\n: ")
        with open("Address.txt", "a") as A:
            A.write("\n{}".format(Address))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        Home_Number = input("\nEnter Home Number of "+Name+": ")
        with open("Home Number.txt", "a") as HN:
            HN.write("\n{}".format(Home_Number))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        Mobile_Number = input ("\nEnter Mobile Number of "+Name+": ")
        with open("Mobile Number.txt", "a") as MN:
            MN.write("\n{}".format(Mobile_Number))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        Email_Address = input ("\nEnter Email Address of "+Name+": ")
        with open("Email Address.txt", "a") as EA:
            EA.write("\n{}".format(Email_Address))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        Dietry_Needs = input("\nEnter Medical/Dietry Needs of "+Name+": ")
        with open("Medical Dietry Needs.txt", "a") as MDN:
            MDN.write("\n{}".format(Dietry_Needs))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        print ("All information for "+Name+" has been added. Redirecting Back To Main...")
        time.sleep(5)
        Main()

    elif ATD == "B" or ATD == "b":
        Main()

def CheckDatabase():
    print ("====Check Database===== \nA)Would you like to check details? \nB)Check if they are a member?")
    TC = input(": ")
    if TC == "A" or TC == "a":
        NameDetail = input ("Please enter the name you would like to check the details of.\nThis will only work if they are a member\n: ")
        with open('Name.txt') as ND:
            for number, line in enumerate(ND, 1):
                if (str(NameDetail)) in line:
                    Number, junk = number, line in enumerate(ND, 1)
                    print ("\nName = ", NameDetail)

                    A = open("Address.txt", "r")
                    AData =[line.rstrip() for line in A.readlines()]
                    print ("Address = ",(AData[number]))

                    HN = open("Home Number.txt", "r")
                    HNData =[line.rstrip() for line in HN.readlines()]
                    print ("Home Number = ",(HNData[Number]))

                    MN = open("Mobile Number.txt", "r")
                    MNData =[line.rstrip() for line in MN.readlines()]
                    print ("Mobile Number = ",(MNData[Number]))

                    EAS = open("Email Address.txt", "r")
                    EAData =[line.rstrip() for line in EAS.readlines()]
                    print ("Email Address = ",(EAData[Number]))

                    MDND = open("Email Address.txt", "r")
                    MDNData =[line.rstrip() for line in MDND.readlines()]
                    print ("Medical/Dietry Needs = ",(MDNData[Number]))


                else:
                    print ("Person not found!")

    elif TC == "B" or TC == "b":
        NameChoice = input("Enter persons name: ")
        with open('Name.txt') as NAME:
            for number, line in enumerate(NAME, 1):
                if (str(NameChoice)) in line:
                    print (NameChoice)
                    print ("is a member")
                else:
                    print ("Not a member!")


def Main():
    print ("\nSVA of UK Database")
    while True:
        print ("\nA)Check Database \nB)Add to Database \nC)Exit Program")
        choice = input(": ")

        if choice == "A" or choice == "a":
            CheckDatabase()

        elif choice == "B" or choice == "b":
            AddToDatabase()

        elif choice == "C" or choice == "c":
            break

        else:
            print ("Invalid Input")
            Main()

Main()
SVA of UK Database

A)Check Database 
B)Add to Database 
C)Exit Program
: A
====Check Database===== 
A)Would you like to check details? 
B)Check if they are a member?
: A
Please enter the name you would like to check the details of.
This will only work if they are a member
: Sagar Bharadia

Name =  Sagar Bharadia
1
Traceback (most recent call last):
  File "H:\SVA UK PROGRAM\SVA of UK.py", line 126, in <module>
    Main()
  File "H:\SVA UK PROGRAM\SVA of UK.py", line 114, in Main
    CheckDatabase()
  File "H:\SVA UK PROGRAM\SVA of UK.py", line 74, in CheckDatabase
    print ("Address = ",(AData[Number]))
IndexError: list index out of range
>>> 
编辑2: Name.txt:

Sagar Bharadia
地址.txt

8 John Road
Home Number.txt

02089563524
02045745854
手机号码.txt

02089563524
02045745854
医学营养学需要.txt

None
编辑3:

import time

def AddToDatabase():
    print ("\nYou are adding to the Database. \nA)Continue \nB)Go Back")
    ATD = input(": ")
    if ATD == "A" or ATD == "a":

        Name = input("\nEnter Name of Member [First Name and Surname]: ")
        with open("Name.txt", "a") as N:
            N.write("\n{}".format(Name))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        print ("\nEnter Address of "+Name+" all on one line")
        print ("In format [Include Commas]")
        print ("\nRoad name with house number [e.g. 1 Morgan Way], Borough [e.g Harrow], City [e.g London], Postcode [e.g. HA5 2EF]")
        Address = input("\n: ")
        with open("Address.txt", "a") as A:
            A.write("\n{}".format(Address))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        Home_Number = input("\nEnter Home Number of "+Name+": ")
        with open("Home Number.txt", "a") as HN:
            HN.write("\n{}".format(Home_Number))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        Mobile_Number = input ("\nEnter Mobile Number of "+Name+": ")
        with open("Mobile Number.txt", "a") as MN:
            MN.write("\n{}".format(Mobile_Number))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        Email_Address = input ("\nEnter Email Address of "+Name+": ")
        with open("Email Address.txt", "a") as EA:
            EA.write("\n{}".format(Email_Address))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        Dietry_Needs = input("\nEnter Medical/Dietry Needs of "+Name+": ")
        with open("Medical Dietry Needs.txt", "a") as MDN:
            MDN.write("\n{}".format(Dietry_Needs))
        time.sleep(1)
        print ("\nAdding...")
        time.sleep(1)

        print ("All information for "+Name+" has been added. Redirecting Back To Main...")
        time.sleep(5)
        Main()

    elif ATD == "B" or ATD == "b":
        Main()

def CheckDatabase():
    print ("====Check Database===== \nA)Would you like to check details? \nB)Check if they are a member?")
    TC = input(": ")
    if TC == "A" or TC == "a":
        NameDetail = input ("Please enter the name you would like to check the details of.\nThis will only work if they are a member\n: ")
        with open('Name.txt') as ND:
            for number, line in enumerate(ND, 1):
                if (str(NameDetail)) in line:
                    Number, junk = number, line in enumerate(ND, 1)
                    print ("\nName = ", NameDetail)

                    A = open("Address.txt", "r")
                    AData =[line.rstrip() for line in A.readlines()]
                    print ("Address = ",(AData[number]))

                    HN = open("Home Number.txt", "r")
                    HNData =[line.rstrip() for line in HN.readlines()]
                    print ("Home Number = ",(HNData[Number]))

                    MN = open("Mobile Number.txt", "r")
                    MNData =[line.rstrip() for line in MN.readlines()]
                    print ("Mobile Number = ",(MNData[Number]))

                    EAS = open("Email Address.txt", "r")
                    EAData =[line.rstrip() for line in EAS.readlines()]
                    print ("Email Address = ",(EAData[Number]))

                    MDND = open("Email Address.txt", "r")
                    MDNData =[line.rstrip() for line in MDND.readlines()]
                    print ("Medical/Dietry Needs = ",(MDNData[Number]))


                else:
                    print ("Person not found!")

    elif TC == "B" or TC == "b":
        NameChoice = input("Enter persons name: ")
        with open('Name.txt') as NAME:
            for number, line in enumerate(NAME, 1):
                if (str(NameChoice)) in line:
                    print (NameChoice)
                    print ("is a member")
                else:
                    print ("Not a member!")


def Main():
    print ("\nSVA of UK Database")
    while True:
        print ("\nA)Check Database \nB)Add to Database \nC)Exit Program")
        choice = input(": ")

        if choice == "A" or choice == "a":
            CheckDatabase()

        elif choice == "B" or choice == "b":
            AddToDatabase()

        elif choice == "C" or choice == "c":
            break

        else:
            print ("Invalid Input")
            Main()

Main()
SVA of UK Database

A)Check Database 
B)Add to Database 
C)Exit Program
: A
====Check Database===== 
A)Would you like to check details? 
B)Check if they are a member?
: A
Please enter the name you would like to check the details of.
This will only work if they are a member
: Sagar Bharadia

Name =  Sagar Bharadia
1
Traceback (most recent call last):
  File "H:\SVA UK PROGRAM\SVA of UK.py", line 126, in <module>
    Main()
  File "H:\SVA UK PROGRAM\SVA of UK.py", line 114, in Main
    CheckDatabase()
  File "H:\SVA UK PROGRAM\SVA of UK.py", line 74, in CheckDatabase
    print ("Address = ",(AData[Number]))
IndexError: list index out of range
>>> 
英国数据库的SVA A) 检查数据库 B) 添加到数据库 C) 退出程序 :A ===检查数据库=== A) 您想查看详细信息吗? B) 检查他们是否是会员? :A 请输入要检查其详细信息的名称。 这只有在他们是会员的情况下才有效 :Sagar Bharadia Name=Sagar Bharadia 1. 回溯(最近一次呼叫最后一次): 文件“H:\SVA UK PROGRAM\SVA of UK.py”,第126行,在 Main() 文件“H:\SVA UK PROGRAM\SVA of UK.py”,第114行,主目录 检查数据库() CheckDatabase中的第74行文件“H:\SVA UK PROGRAM\SVA of UK.py” 打印(“地址=,(数据[编号]) 索引器:列表索引超出范围 >>>
当您在枚举(ND,1)中执行
Number=Number时,将
Number
定义为元组。您已经使用
for
循环创建了枚举(ND,1)
中的
编号行。为什么不直接用它呢?i、 e.
AData[number]

仅举一个例子,这就是您将
Number
设置为的内容:

>>> for x, y in enumerate([1,2,3], 1):
        print x, y in enumerate([1,2,3], 1)


1 False
2 False
3 False
它是一个元组,包含来自
for
循环的
数字,以及enumerate(ND,1)
行的值(一个布尔表达式,要么在那里,要么不在那里)

您还有其他几个问题:

  • 通过将
    1
    提供给
    枚举
    ,可以从
    1
    开始
    number
    ,而不是
    0
    。在python中,列表索引从
    0
    开始。因此,如果列表的长度是
    1
    ,那么
    [1]
    处的子索引实际上是超出范围的。您应该从
    0
    开始执行
    enumerate(ND)
  • 您需要
    .close()
    您打开的文件()
,或者像处理第一个文件一样使用
/

  • 您正在打开
    电子邮件地址.txt
    两次。。。你是有意的吗
  • 在这一行:

    Number = number, line in enumerate(ND, 1)
    
    将两个值赋给Number——这将生成一个元组

    你可以这样做:

    Number, junk = number, line in enumerate(ND, 1)
    
    这将导致数字成为单个值,而不再是元组。

    元组是一种“列表”。见以下文件:


    您可能正在为var编号分配2个或更多值

    请提供完整的回溯。但是不需要设置
    Number=Number,line…
    (这使它成为一个元组);您已经有行号了,只需使用
    number
    。这是完整的代码吗?如果有帮助,我可以粘贴完整的代码:)问题只出现在本节中,这就是我只打印此代码的原因subroutine@PythonBeginner对粘贴整个代码。我已经提供了完整的代码供您查看@2RS2TS。它出现了一个错误:indexer错误:list index out of ofrange@PythonBeginner对于
    AData
    和文件中的其他行的内容,而不是您发布的代码的一部分,这是一个完全不同的问题。@pythonbeginer我猜您的
    Name.txt
    中的行数多于其他文本文件中的行数。因此,
    索引器
    编号
    大于
    len(AData)
    )Ok将删除文本文件中所需行以外的所有其他行。我已经删除了这些行,只留下最上面的行,错误仍然出现@2rs2ts现在我真的很困惑,到底是什么问题呢?不,我不是故意要打开Email Address.txt两次的,谢谢你指出这一点。我将切换到一个,并使其与,所以它会自动关闭@2rs2tsI得到相同的错误,当我尝试@2rs2ts的建议。索引器错误:列表索引超出范围修改后的代码仍有以下行:
    Number=Number,枚举(ND,1)
    中的行,这意味着数字是元组而不是整数,因此不能是列表索引。