+ 1

Problem in writing

How should I change the code to print Hello world! ? https://code.sololearn.com/cqqaJFIl671E/?ref=app

24th Feb 2019, 11:15 AM
A Learner
A Learner - avatar
6 Réponses
+ 4
You use the variable "amount_written" to store the return value of the function file.write() and then as a file handle to open the same file again. That's quite confusing. Also, the file is still open when you try to re-open it. That won't work. Open the file in w mode, close it, open it again in r mode and close it again. Or use the file mode w+ for reading and writing access so you don't have to close it between writing and reading operations. This way your code works: msg = "Hello world!" file = open("newfile.txt", "w") amount_written = file.write(msg) file.close() amount_written= open("newfile.txt","r") print(amount_written.read()) amount_written.close()
24th Feb 2019, 12:32 PM
Anna
Anna - avatar
+ 4
You're welcome ☺️ msg = "Hello world!" file = open("newfile.txt", "w+") file.write(msg) file.seek(0) print(file.read()) file.close() file.seek(0) is used to jump back to the beginning of the file so that you can read from the beginning
24th Feb 2019, 1:42 PM
Anna
Anna - avatar
+ 2
Anna thanks🙏🏾😊
24th Feb 2019, 3:14 PM
A Learner
A Learner - avatar
+ 1
It won't work in Sololearn because you can't acces files here.
24th Feb 2019, 11:32 AM
Maneren
Maneren - avatar
24th Feb 2019, 12:01 PM
A Learner
A Learner - avatar
+ 1
Anna thanks a lot... could you write the code with w+, please?
24th Feb 2019, 1:20 PM
A Learner
A Learner - avatar