- 2

I cannot understand this code?? Why the output is 12?!!

https://code.sololearn.com/cXjj9MDIbVV7/?ref=app

21st May 2018, 8:49 PM
Omar
Omar - avatar
10 Answers
+ 4
The amount_written variable receives number of bytes (characters, letters or symbols) written into the file, count how many characters there is in "Hello world!" including space, and you'll understand why it shows 12. You should use print(msg) if you want to see "Hello world!" on screen. Hth, cmiiw
21st May 2018, 9:32 PM
Ipang
+ 3
the size of the word written in the file as space and characters are counted
21st May 2018, 8:53 PM
Shahd Moemen
Shahd Moemen - avatar
+ 2
could you kindly please take a look at "write" specifocation and ask that question again?
21st May 2018, 9:18 PM
Paul
+ 2
#store message msg = "Hello world!" #open output file file = open("newfile.txt", "w") #write the hello world message to the file #get the number of characters written amount_written = file.write(msg) #print the number of characters written print(amount_written) #close the file file.close()
21st May 2018, 9:33 PM
John Wells
John Wells - avatar
+ 2
The variable you are printing is set to the file.write function return. That function always returns the number of characters it writes.
21st May 2018, 9:54 PM
John Wells
John Wells - avatar
+ 1
if you want to get the data written in the file you can use with ... as to read the file and store the data in a variable
21st May 2018, 9:33 PM
Shahd Moemen
Shahd Moemen - avatar
+ 1
I forgot that Python documentstion is a piece of :v Here, from StackOverflow: If, instead, you opened the file in text mode, e.g. f = open(filename, 'w')then f.write() expects a str object, and will return the number of characterswritten, which for multi-byte encodings such as UTF-8 may not match the number of bytes written.
21st May 2018, 9:45 PM
Paul
0
but why it the output isnot Hello world! ?!!
21st May 2018, 9:13 PM
Omar
Omar - avatar
0
I took a look on it but I didnot understand
21st May 2018, 9:25 PM
Omar
Omar - avatar
0
Ok but why it prints the lenght and I didnot use len()
21st May 2018, 9:47 PM
Omar
Omar - avatar