sean
sean

Reputation: 61

Python can't make variable from file

From a file I have an ID in the first column, then the person's name in the second column of the text and the IDs/usernames are separated by lines. I'm trying to make a variable of the second column of the file, the one next to the correct ID however when I attempt this, I get an error stating that the local variable 'realName' referenced before assignment. I have no global variables with in my code as well. Any feedback is appreciated!

fileOpen=("details.txt","r")
ID=input("What is your ID?")
for line in fileOpen:
    details=line.strip().split(",")
    if ID==details[0]:#id will always match something inside the file
        realName=details[1] 
        break
print("Hi, {0}".format(realName)) 

Upvotes: 1

Views: 69

Answers (2)

Monolith
Monolith

Reputation: 1147

You are getting this error because of the if statement isn't running. Making a variable open("filename", "r") does not make that variable a string. It is simply a pointer to a class. Instead, you should do:

fileOpen=("details.txt","r")
ID=input("What is your ID?")
for line in fileOpen.read(): # You need to add the .read() method to make the fileopen variable a string
    details=line.strip().split(",")
    if ID==details[0]: # id will always match something inside the file
        realName=details[1] 
        break
print("Hi, {0}".format(realName)) 

Upvotes: 1

Barmar
Barmar

Reputation: 781058

This will happen if name doesn't match the first field of any of the lines, since you only set realName when you find a match. You can provide a default when this happens using an else: clause:

def userMenu(name):
    fileOpen=("details.txt","r")
    for line in fileOpen:
        details=line.strip().split(",")
        if name==details[0]:
            realName=details[1] 
            break
    else:
        realName = "Unknown user"
    print("hi {0}".format(realName))

Upvotes: 0

Related Questions