PythonBeginner
PythonBeginner

Reputation: 169

How to assign a Line Number from a text file to a variable?

I am trying to print the variable 'Number' But it come up with a error.

'TypeError: list indices must be integers, not tuple'

I dont understand? What is a tuple and how could i fix this problem? How do i assign a line number in a text file to a variable?

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!")

EDIT:

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()

EDIT 2: Name.txt :

Sagar Bharadia

Address.txt

8 John Road

Home Number.txt

02089563524

Mobile Number.txt

02045745854

Medical Dietry Needs.txt

None

EDIT 3:

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
>>> 

Upvotes: 1

Views: 1491

Answers (3)

2rs2ts
2rs2ts

Reputation: 11026

You define Number as a tuple when you do Number = number, line in enumerate(ND, 1). You already created number, line in enumerate(ND, 1) with your for loop anyway. Why not just use that? i.e. AData[number].

Just using an example, this is what essentially what you are setting Number to:

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


1 False
2 False
3 False

It is a tuple containing the number from your for loop, and the value of line in enumerate(ND, 1) (a boolean expression, either it's in there or it's not).

You also have several other problems:

  • You start number at 1 instead of 0 by providing the 1 to enumerate. In python, list indices start at 0. So if the length of a list is 1 then sub-indexing at [1] is actually out of bounds. You should be doing enumerate(ND) instead to start at 0.
  • You need to .close() your files that you open(), or use with/as like you do with your first file.
  • You are opening Email Address.txt twice... did you mean to do that?

Upvotes: 2

gdlm
gdlm

Reputation: 353

Tuples are a kind of a "list". See doc on:

http://docs.python.org/release/1.5.1p1/tut/tuples.html

You are probably assigning 2 or more values for the var Number

Upvotes: 0

Chris Johnson
Chris Johnson

Reputation: 21956

In this line:

Number = number, line in enumerate(ND, 1)

You are assigning two values to Number -- this produces a tuple.

You could do something like this:

Number, junk = number, line in enumerate(ND, 1)

This would result in Number being a single value, no longer a tuple.

Upvotes: 0

Related Questions