+ 1
Problem in writing
How should I change the code to print Hello world! ? https://code.sololearn.com/cqqaJFIl671E/?ref=app
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()
+ 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
+ 2
Anna thanks🙏🏾😊
+ 1
It won't work in Sololearn because you can't acces files here.
+ 1
Maneren
so ; why this one works?
https://code.sololearn.com/cqCSxU4cMZTn/?ref=app
+ 1
Anna thanks a lot... could you write the code with w+, please?