0

why py executes the write method in line 2?

i was expecting it to assign that to a variable x and it will do the actual writing only when i call the x. i dont understand... i thought it will be a blank file. file = open("newfile.txt", "w") x=file.write("Some new text66776") print(x) file.close() file = open("newfile.txt", "r") print("Reading new contents") print(file.read()) print("Finished") file.close()

3rd Aug 2016, 9:34 AM
Laura
Laura - avatar
2 Réponses
+ 2
The nature of python always executes a function if you give it a variable and x stores the return value of file.write() if you want to store the function in a variable, do something like: x = file.write x("the new text")
3rd Aug 2016, 9:41 AM
Frederik Fleischmann
Frederik Fleischmann - avatar
+ 1
great, thank you! :)
3rd Aug 2016, 9:43 AM
Laura
Laura - avatar