Python File writelines() Method

Python File(文件) 方法Python File Methods


Overview

writelines()This method is used to write a sequence of strings to a file.

This sequence of strings can be produced by an iterable object, such as a list of strings.

For line breaks, you need to specify the newline character \n.

Syntax

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

fileObject.writelines( [ str ])

Parameters

  • str-- The sequence of strings to be written to the file.

Return Value

This method has no return value.

Example

The following example demonstrates the use of the writelines() method:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开文件
fo = open("test.txt", "w")
print "文件名为: ", fo.name
seq = ["Example 1\n", "Example 2"]
fo.writelines( seq )

# 关闭文件
fo.close()

The output of the above example is:

文件名为:  test.txt

View the file content:

$ cat test.txt 
Example 1
Example 2

Python File(文件) 方法Python File Methods

Other Extensions