Python - How to write a file in Python -- File writer/scanner(file) equivalent


Writing Files



To write to files you use the write method, which writes a string to the file.
For example:
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()
The "w" mode will create a file, if it does not already exist.

When a file is opened in write mode, the file's existing content is deleted.


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

To write something other than a string, it needs to be converted to a string first.



Comments

Popular posts from this blog

Python - Argument Passing

Python - How to Escape special characters in String