Monday, October 3, 2016

[ Exceptions & Files ] Writing Files

file = open("filename.txt","w")
file.write("This has been written to a file")
file.close

file = open("filename.txt","r")
print(file.read())
file.close

"w" mode will create a file , if it does not ready exist.


When a file is opened in write mode , the file's existing content is deleted.
As you can see, the content of the file has been overwritten.

The write method returns the number of bytes written to a file , it successful

msg = "Hello World"
file = open("newfile.txt",'w")
amount_written = file.write(msg) # == len(msg)
print(amount_written)
file.close()

No comments:

Post a Comment