English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
write() This method is used to write a specified string to the file.
Before the file is closed or the buffer is refreshed, the string content is stored in the buffer, and you can't see the written content in the file at this time.
If the file open mode includes b, the str (parameter) must be converted to bytes form using the encode method when writing file content, otherwise an error will be reported: TypeError: a bytes-like object is required, not 'str'.
The syntax of the write() method is as follows:
fileObject.write( [ str ])
str -- The string to be written to the file.
It returns the length of the written characters.
The following example demonstrates the use of the write() method:
# Open the file fo = open("test.txt", "w") print("File name: ", fo.name) str = "Basic tutorial network" fo.write( str ) # Close the file fo.close()
The output result of the above example is:
File name: test.txt
View file content:
$ cat test.txt Basic tutorial network