0

I am new to Python and please excuse if my question sounds dumb. I have a function which reads a text file and records the first line and passes the same to another function. But I am not able to figure out a way to store the value to a global variable which can be reused again.

Sample of text file. Holds only one line: 1234567

Script to read file:

def main():
    input = file(infile, 'r')
    lines = input.readlines()
    input.close()
    i = 0
    for line in lines:
        i += 1
        id = int(line)
        WorkOnIDThread(id)
main()

So basically I want help with storing the id as a global variable which I could reuse through out the script.

Any help on this would be really helpful.

jramirez
  • 8,537
  • 7
  • 33
  • 46
daaredevill
  • 31
  • 3
  • 8

2 Answers2

0

If you just want to share with other function, use global

id = 0
def main():
    global id
    ...
PasteBT
  • 2,128
  • 16
  • 17
-1
id = 0 # declare it in the global scope

def main():
    # using the global keyword will let you access it in the function scope
    global id 
    input = file(infile, 'r')
    lines = input.readlines()
    input.close()
    i = 0
    for line in lines:
        i += 1
        id = int(line)
        WorkOnIDThread(id)
main()
print id
jramirez
  • 8,537
  • 7
  • 33
  • 46
  • Thank you very much.. That exactly what i did just now to fix the issue and by the time I figured it out to wanted to come back and say all is well I saw the response. Thank again for the help!!! – daaredevill Nov 22 '13 at 22:52
  • 1
    Except that using the variable name of `id` is particularly bad, considering it overwrites the built-in `id()` function. – VooDooNOFX Nov 22 '13 at 23:16
  • 1
    Agree.. ID was just used for representation. Used a different naming convention.. Thanks! – daaredevill Nov 24 '13 at 16:15