如何在不知道名称的情况下在另一个文件中查找和使用变量?

问题描述 投票:1回答:1

我正在用python编写程序,该程序需要输入用户名,并使用来自单独文本文件的单词为该用户提供昵称或“新名称”。

#This file takes a name input from the user, gives the user a new name, and then saves the username and #new name in a separate "companion" file.
import random
import NameGenCompanion as NGC
unloggedname=1
Dict = open('Dictionary.txt').read().splitlines()
line1 = random.choice(Dict)
line2 = random.choice(Dict)
clear1 = line1.replace("#", "")
clear2 = line2.replace("#","")
word1 = clear1.replace("%","")
word2 = clear2.replace("%","")
newname = word1 + "-" + word2
username = input("What is your name? ")
Lo = open("NameGenCompanion.py").read()
if username in Lo:
    unloggedname=0
    print()#whatever the username variable was assigned in the companion file
if unloggedname!=0:
    Log = open('NameGenCompanion.py','a')
    Log.write("\n" + username + ' = ' + "'" + newname + "'")
    Log.close()
    print(username + "'s new name is " + newname)

程序将用户名和昵称保存到“伴侣文件”。

示例:如果我的名字是“ John”,给定的昵称是“ Appleseed”,那么我的程序会将其写入伴随文件:

John = 'Appleseed'

然后,如果我返回程序,并为其提供相同的用户名,我希望它在伴随文件中找到变量John,并将该变量的值分配给原始文件中的newname

问题是,我不知道如何使程序在伴随文件中找到用户名,然后在原始文件中使用该变量。如何在NameGenCompanion中导入和使用名称与原始文件中的username相同的任何给定变量?

python persistence
1个回答
0
投票

这是一个很糟糕的主意,原因有很多(eg,对于其中带有'的名称,它[sys.path的坏处)),但是答案很简单:getattr(NameGenCompanion,username)具有读取变量名称的效果,该变量的名称被选择为[[dynamically]]。您甚至可以使用getattr(NameGenCompanion,username,None)比使用Lo更简单,更可靠地处理新名称。

© www.soinside.com 2019 - 2024. All rights reserved.