EvilZone
Programming and Scripting => Scripting Languages => : 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 =)
-
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).
-
It's not "writeFile.close", it is "writeFile.close()" since it is a function.
-
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?
-
Are you sure it's a security measure or simply how scoping works in Python?
heh yes, that too.
-
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