Getting KeyError when trying to create multiple variables in for loop ("post0", "post1", etc.)

59 views Asked by At

Very new to python - just started actually using it yesterday. I'm running a for loop that scans a text file and copies specific parts of it into variables that will then be put into a class "post". I want to create a new post at the bottom of the loop, named "post0", "post1", and so on, corresponding with the number of times the for loop has been run. This is what I'm trying to use:

postname = globals()['post%s' % s]

And I currently am trying to have it print the name of the post every time it creates one with a simple print(postname). 's' is the variable the for loop runs off of, if that makes sense. It starts at 0 and runs up to the number of lines in the text file, currently 424.

When I run the code, it returns "KeyError: post0". What am I doing wrong?

Also, reading around here it seems that creating variables this way is bad practice. If there is a more efficient way to do it I'd be happy to try that instead, but I'd also like to know how to make this method work just so I understand the concept. Thanks.

Edit: Problem solved! See my answer below.

1

There are 1 answers

0
Patrick Miles On

I created a list postlist = [] outside of the loop, then inside the loop I append the list with a "post_" where "_" is the 's' variable. Looks like this:

postlist.append('post%s' % s)

Python is cool!