in Python I’m trying to set a variable from info stored in a txt. I can manage to set it, but it does not act as a number. Is it being stored as something else?
Here is my .txt file (all info is written on one line, no \ns):
11 14 15 3
Here is my script:
def break_words(text):
words = text.split(' ')
return words
file_name = open("set_initial.txt")
words = break_words(file_name.read())
shift_l1 = words[0]
shift_l2 = words[1]
shift_l3 = words[2]
shift_l4 = words[3]
shift_l5 = words[4]
shift_l6 = words[5]
# this part is to verify that the variables are being set:
print shift_l1, shift_l2, shift_l3, shift_l4
while shift_l4 < 28:
# and the script goes on into a loop from here
I am using this method because the length of the values in the txt will change (for example to: 114 34 2 4318). When I run the script, the print function works fine and returns my variables as the numbers I have in my .txt (11 14 15 3 respectively), so shift_l4 prints out as 3, so my WHILE loop should be functioning. But it’s not. As I said, I figure my variables aren’t being set to the number value of the numbers in the .txt, but maybe just the text value? I don’t know how to fix it though. Any help or ideas?
Thank you
“file_name” is not a good name for a file object. “words” is not a good name for a collection of numbers represented as strings. “shift_l5 = words[4]” and “shift_l6 = words[5]” will fail, because you have only 4 numbers.
Note that
print "3"andprint 3produce the same results. Useprint repr(something)instead of justprint somethingto get a handle on what data you actually have.Try this: