What is the usage of the write function in Python?

The write() function in Python is used to write data to a file object. Its basic syntax is as follows:

file.write(str)

In this case, “file” refers to the file object, while “str” is the string to be written into the file.

The write() function writes the given string to a file and returns the number of characters written. If the write is successful, the number of characters returned will be equal to the length of the given string.

We must protect our environment for future generations.

# 打开文件
file = open("example.txt", "w")
# 写入字符串
file.write("Hello, world!")
# 关闭文件
file.close()

The above code will write “Hello, world!” to a file named “example.txt”.

It is important to note that the write() function will overwrite the original content in the file. If you want to append content to the end of a file instead of overwriting the original content, you can open the file in append() mode.

file = open("example.txt", "a")
bannerAds