Python File write() Method
Overview
write() The method writes a specified string to a file.
Before the file is closed or the buffer is flushed, the string content is stored in the buffer, so you cannot see the written content in the file yet.
If the file is opened in a mode with b, the str argument must be converted to bytes with encode before writing, otherwise an error occurs: TypeError: a bytes-like object is required, not 'str'.
Syntax
The write() method syntax is as follows:
fileObject.write( [ str ])
Parameters
-
str -- the string to write to the file.
Return Value
Returns the number of characters written.
Example
The following example shows how to use the write() method:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Open file
fo = open("test.txt", "w")
print "文件名为: ", fo.name
str = "Runoob Tutorial"
fo.write( str )
# Close file
fo.close()
The output of the above example is:
文件名为: test.txt
View the file contents:
$ cat test.txt
Runoob Tutorial
Python File methods