English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Fonctions en Python

Types de données en Python

Python file operation

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python file write() usage and example

Python File (File) Method

Overview

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'.

Syntax

The syntax of the write() method is as follows:

fileObject.write( [ str ])

Parameter

  • str -- The string to be written to the file.

Return value

It returns the length of the written characters.

Example

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

Python File (File) Method