EvilZone

Programming and Scripting => Scripting Languages => : Moistfish January 11, 2014, 03:54:15 PM

: Question: Help my understanding of my code
: Moistfish January 11, 2014, 03:54:15 PM
Hello,  learning python atm and came across this below.  Wanted to know if anyone knew why this happened


This one didn't write anything to the test.txt file


:
writeFile = open(r'C:/Documents and Settings/MyComp/Desktop/Python/test.txt', 'w')

def main():
   
   name1 = "Joe"
   name2 = "James"
   name3 = "Johnny"

   writeFile.write(name1)
   writeFile.write(name2)
   writeFile.write(name3)

   writeFile.close

main()



and this one did




:
def main():
   
   writeFile = open(r'C:/Documents and Settings/MyComp/Desktop/Python/test.txt', 'w')

   name1 = "Joe"
   name2 = "James"
   name3 = "Johnny"

   writeFile.write(name1)
   writeFile.write(name2)
   writeFile.write(name3)

   writeFile.close

main()


I obviously fixed it, but the question is more for my understanding why it works and writes to the test file when the open command is called within the function, rather than outside it.


Thanks for the help =)
: Re: Question: Help my understanding of my code
: Kulverstukas January 11, 2014, 04:17:05 PM
In the first block of code "writeFile" is considered as a global variable. Python, as well as PHP, have a security measure from accidental usage of global variables. Try adding "global writeFile" just below the function definition (below the DEF line).
: Re: Question: Help my understanding of my code
: s3my0n January 11, 2014, 04:26:45 PM
It's not "writeFile.close", it is "writeFile.close()" since it is a function.
: Re: Question: Help my understanding of my code
: vezzy January 11, 2014, 04:27:11 PM
In the first block of code "writeFile" is considered as a global variable. Python, as well as PHP, have a security measure from accidental usage of global variables. Try adding "global writeFile" just below the function definition (below the DEF line).

Are you sure it's a security measure or simply how scoping works in Python?
: Re: Question: Help my understanding of my code
: Kulverstukas January 11, 2014, 07:04:06 PM
Are you sure it's a security measure or simply how scoping works in Python?
heh yes, that too.
: Re: Question: Help my understanding of my code
: Moistfish January 11, 2014, 07:24:29 PM
It's not "writeFile.close", it is "writeFile.close()" since it is a function.


Yea thanks, typo when repeating the code.  Originally wrote the program on my laptop, wrote this post on my main PC.


Thanks guys =) i shall go and check out scoping in python