Python File write() Method
Overview
write()This method is used to write the specified string to a file.
Before the file is closed or the buffer is flushed, the string content is stored in the buffer, and you cannot see the written content in the file at this time.
If the file opening mode includes b, then when writing file content, the str (parameter) must be converted to bytes form using the encode method, otherwise an error is raised: TypeError: a bytes-like object is required, not 'str'.
Syntax
The syntax of the write() method is as follows:
fileObject.write( [ str ])
Parameters
-
str-- The string to be written to the file.
Return Value
Returns the number of characters written.
Example
The following example demonstrates the use of the write() method:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开文件
fo = open("test.txt", "w")
print "文件名为: ", fo.name
str = "Example"
fo.write( str )
# 关闭文件
fo.close()
The output of the above example is:
文件名为: test.txt
View the file content:
$ cat test.txt ExampleOther Extensions
Python File Methods