1

I am writing a program in python that takes an input for a username, and gives that user a nickname or "new name" from words from a separate text file.

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

The program saves the username and nickname to a "companion file".

Example: If my name is "John" and my given nickname is "Appleseed" then my program writes this to the companion file:

John = 'Appleseed'

Then, if I return to the program, and give it the same username, I want it to find variable John in the companion file, and assign the value of that variable to newname in the original file.

The issue is that I don't know how to make my program find username in the companion file, and then use that variable in the original file. How do I import and use any given variable in NameGenCompanion whose name is the same as username in the original file?

martineau
  • 119,623
  • 25
  • 170
  • 301
Leyvori
  • 41
  • 1
  • 1
    Don't use a Python file for variable storage; use e.g. JSON instead. – AKX Jan 01 '20 at 18:22
  • you can use `.ini` files with [`configparser`](https://docs.python.org/3/library/configparser.html#module-configparser) – Tomerikoo Jan 01 '20 at 18:24
  • I think your approach may be sub-optimal. You could store the name pairs (mapping usernames to nicknames) in a Python dictionary and save _that_ object, which you can easily load (and update then re-save as necessary). See my answer to [Saving an Object (Data persistence)](https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence). – martineau Jan 01 '20 at 19:03

1 Answers1

0

This is a terrible idea for many reasons (e.g., it misbehaves arbitrarily for names with ' in them (with this naïve implementation) and it assumes bad things about sys.path), but the answer is easy: getattr(NameGenCompanion,username) has the desired effect of reading a variable whose name is chosen dynamically. You can even use getattr(NameGenCompanion,username,None) to handle the new-name case more simply and more reliably than with Lo.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76