【问题标题】:Python can't make variable from filePython无法从文件中生成变量
【发布时间】:2018-09-07 17:49:21
【问题描述】:

从一个文件中,我在第一列中有一个 ID,然后在文本的第二列中的人名和 ID/用户名由行分隔。我正在尝试为文件的第二列创建一个变量,即正确 ID 旁边的变量,但是当我尝试这样做时,我收到一个错误,指出在分配之前引用了局部变量“realName”。我的代码中也没有全局变量。任何反馈表示赞赏!

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

【问题讨论】:

  • 请提供一个简短的完整程序来演示该问题。由于无法重现问题,我们只能猜测。请参阅minimal reproducible example 了解更多信息。
  • 如果没有一行符合条件name == details[0],你永远不会设置realName,所以你会得到那个错误。

标签: python python-3.x file variables


【解决方案1】:

如果name 不匹配任何行的第一个字段,就会发生这种情况,因为您只有在找到匹配项时才设置realName。当发生这种情况时,您可以使用 else: 子句提供默认值:

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

【讨论】:

  • 即使输入 100% 正确的用户名,我也会得到未知用户。有什么想法吗?
  • 我建议你在循环中添加一个打印语句,这样你就可以看到details[0]是什么。
  • 你能发一份文件内容的样本吗?
  • 文件中逗号后面有空格吗?
  • 我在 if 语句后添加了一个 'print("user found'打印语句@Barmar
【解决方案2】:

您收到此错误是因为 if 语句未运行。使变量 open("filename", "r") 不会使该变量成为字符串。它只是一个指向类的指针。相反,您应该这样做:

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

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多