Python File Write
# Python2.x Python File write() Method
[ Python File Methods](#)
* * *
### Overview
The **write()** method is used to write a 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 contains b, when writing content to the file, the str (parameter) needs to be converted to bytes form using the encode method, otherwise an error will be reported: TypeError: a bytes-like object is required, not 'str'.
### Syntax
The syntax of the write() method is as follows:
fileObject.write( )
### Parameters
* **str** -- The string to be written to the file.
### Return Value
Returns the length of the written characters.
### Example
The following example demonstrates the use of the write() method:
#!/usr/bin/python# -*- coding: UTF-8 -*-# Open file fo = open("test.txt", "w")print "File name: ", fo.name str = "" fo.write( str )# Close file fo.close()
The output result of the above example is:
File name: test.txt
View file content:
$ cat test.txt
[ Python File Methods](#)
YouTip