1

So, I'm making a program (hopefully) that is an 'improved' command prompt.
In my program, I want it to get all lines from a text file.
The text file will contain lines that look like this:

desktop=C:\Users\%username%\Desktop
scripts=D:\Scripts

What I want my program to do, is to read through that, and create new variables such as:

desktop = "C:\Users\%username%\Desktop"
scripts = "D:\Scripts"

I know there are probably better and safer ways to do this, but for now, I'd like to do it this way. Here is my code so far (it doesn't work):

with open("custom_shortcuts.txt","r") as f:
    customShortcuts = [x.strip('\n') for x in f.readlines()]
for i in customShortcuts:
    parts = i.split("=")
    varName = str(parts[0])
    varValue = str(parts[1])
    eval("varName = varValue")

As you can see, I tried to use eval(), and failed.

0

1 Answer 1

5

Can you work with dictionaries instead?

text = r'''desktop=C:\Users\%username%\Desktop
scripts=D:\Scripts'''

var = dict(line.strip().split('=') for line in text.splitlines())
print(var)
{'desktop': 'C:\\Users\\%username%\\Desktop', 'scripts': 'D:\\Scripts'}

It isn't good practice to dynamically inject variables into your namespace. If you want the value for desktop, you'd access it as var['desktop'].

Sign up to request clarification or add additional context in comments.

1 Comment

This seems like a better idea, thanks. I'll try it out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.