0

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?

pwn'cat
  • 111
  • 1
  • 6

1 Answers1

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