Home  >  Article  >  Backend Development  >  python file write () method summary and function analysis (example)

python file write () method summary and function analysis (example)

乌拉乌拉~
乌拉乌拉~Original
2018-08-16 17:36:525781browse

In today’s article, let’s learn about pythonwrite(). I will explain the write method in python in this article. And pythonwrite attribute and will also explain where it can be used in python programming. Without further ado, let’s get started.

Overview

The write() method is used to write the specified string to the file.

Before the file is closed or the buffer is refreshed, the string content is stored in the buffer. At this time, you cannot see the written content in the file.

If the file opening mode has b, then when writing the file content, str (parameter) must be converted into bytes form using the encode method, otherwise an error will be reported: TypeError: a bytes-like object is required, not 'str' .

Syntax

The write() method syntax is as follows:

fileObject.write( [ str ])

Parameters

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

Return value

#Returns the length of characters written.

Examples

The following examples demonstrate the use of the write() method:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开文件
fo = open("test.txt", "w")
print "文件名为: ", fo.name
str = "天天开心"
fo.write( str )
# 关闭文件
fo.close()

The output result of the above example is:

文件名为:  test.txt

View the file content:

$ cat test.txt 
天天开心

In this article, we explain what write( ) method, if you don’t understand it, you can give it a try. After all, hands-on practice is the best way to verify what you have learned. Finally, I hope this article can bring some help to you who are learning python.

For more related knowledge, please visit the Python tutorial column on the php Chinese website.

The above is the detailed content of python file write () method summary and function analysis (example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn