-1

I've been really frustrated with an error I keep getting, no matter what I attempt. I'm trying to make variables out of a list words from a file and set them to an empty string (for later use).

Here's the code snippet:

values = []
input_values = open('list.txt')
for i in input_values.readlines():
    i = i.strip("\n")
    values.append(str(i))
for i in values:
    exec(str(i) + " = ''")

And here's the output:

Traceback (most recent call last):
  File "script.py", line 59, in <module>
    exec(str(i) + " = ''")
  File "<string>", line 2
    = ''
    ^
IndentationError: unexpected indent

I've also tried without using for i in values but still got the same output. And what strange is that I can print the value, but not use it. If I add print i after the strip() line, then line1 gets added to the top of the output.

So this:

values = []
input_values = open('list.txt')
for i in input_values.readlines():
    i = i.strip("\n")
    print i
    values.append(str(i))
    exec(str(i) + " = ''")

Yields this:

line1
Traceback (most recent call last):
  File "script.py", line 59, in <module>
    exec(str(i) + " = ''")
  File "<string>", line 2
    = ''
    ^
IndentationError: unexpected indent

What am I doing wrong?

7
  • Why do you want to do this? I suspect that what you really need is a dict. See stackoverflow.com/questions/5036700/… Commented Feb 4, 2016 at 10:40
  • @PM2Ring I'm making a script, emulating msfconsole from the Metasploit Framework. Variables need setting, resetting, sending as command line arguments when executing outside scripts, etc. Commented Feb 4, 2016 at 11:06
  • Have you got a blank line in your input file ? Commented Feb 4, 2016 at 11:30
  • @CMDej No, there are no blank lines. Commented Feb 4, 2016 at 11:34
  • 1
    Yes there is a blank line, at the end of the file, with a space. Commented Feb 4, 2016 at 11:44

1 Answer 1

2

There is at least one empty line at the end of your file, with a space, which causes the error. You'd want to strip the whitespace out of all lines and then check if they're empty, before appending them to the list:

values = []
input_values = open('list.txt')
for i in input_values.readlines():
    i = i.strip()
    if i:
        values.append(str(i))
for i in values:
    exec(str(i) + " = ''")

Also, the .readlines is unnecessary, values is unnecessary and even exec is completely unnecessary - instead you could use this:

with open('list.txt') as input_values:
    for i in input_values:
        i = i.strip()
        if i:
            globals()[i] = ''

though it wouldn't complain if you tried to set a variable named 5 for example

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.