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

Basic Python Tutorial

Flow Control in Python

Fonctions en Python

Types de données en Python

File Operations in Python

Objects and Classes in Python

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Usage and example of Python file writelines()

Methods of Python File (File)

Overview

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

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

A newline needs to be specified with the newline character \n.

Syntax

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

fileObject.writelines([str])

Parameter

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

Return value

This method does not return a value.

Example

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

# Open the file
fo = open("test.txt", "w")
print("File name: ", fo.name)
seq = ["Basic Tutorial Website 1\n", "Basic Tutorial Website 2"]
fo.writelines(seq)
# 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 Website 1
Basic Tutorial Website 2

Methods of Python File (File)