0

Why write method is behaving differently in code 1 and code 2. In code1 it is writing and in code2 it is returning length of msg

CODE 1: file = open("newfile.txt", "w") file.write("This has been written to a file") file.close() file = open("newfile.txt", "r") print(file.read()) file.close() CODE2: msg = "Hello world!" file = open("newfile.txt", "w") amount_written = file.write(msg) print(amount_written) file.close()

19th Aug 2020, 2:31 PM
Gubbala Saisree
Gubbala Saisree - avatar
3 Answers
+ 2
probably both (writing and returning length is haplening) the whole time, but you dont use the returned length in Case1 and you dont look in the file afterwards in case 2....
19th Aug 2020, 2:41 PM
Alexander Thiem
Alexander Thiem - avatar
+ 2
Write method is doing same thing in both the codes and that's writing to newfile.txt and returning number of charecters written. Have you read the code you posted ? print() function was passed different argument in both codes. in first code : print(file.read()) file.read() returns content of file as a string and then print method prints this returned in second code: amount_written = file.write(msg) file.write() method returns number of charecters written to file. this returned value is stored in variable amount_written and then printed using print()
19th Aug 2020, 2:45 PM
šŸ‡®šŸ‡³OmkaršŸ•‰
šŸ‡®šŸ‡³OmkaršŸ•‰ - avatar
+ 1
It looks like you are printing the write() function and while that is syntactically correct I am assuming it is semantically incorrect, it does not have the results you want... you should call the write function as you did in CODE 1 and then read the results as you did in CODE 1 https://en.wikipedia.org/wiki/Python_syntax_and_semantics Also, sys.stdout.write returns string length and when you are printing file.write() aka sys.stdout.write, you will get the length of the string https://stackoverflow.com/questions/32576576/sys-stdout-write-in-python3-adds-11-at-end-of-string Lastly, I would reconsider these options for file handling. You should research the "with open()..." syntax for file handling, it is more efficient and secure
19th Aug 2020, 2:44 PM
Steven M
Steven M - avatar