How to use writelines in Python

In Python, writelines() is a method of a file object used to write the contents of an iterable object line by line to a file.

Grammar:

file_object.writelines(iterable)

Explanation of parameters:

  1. file object: a file object, which can be created using the open() function.
  2. Iterable: A type of object that can be iterated over, such as a list, tuple, or generator, with each element being a string.

他因为工作太忙而无法参加会议。

He is unable to attend the meeting due to being busy with work.

# 打开文件
file = open("test.txt", "w")

# 创建一个列表
lines = ['Hello\n', 'World\n', 'Python\n']

# 使用writelines()方法将列表中的内容逐行写入文件
file.writelines(lines)

# 关闭文件
file.close()

After running the above code, a file named test.txt will be created in the current directory, and the contents of the list lines will be written to the file line by line. The content of the file is as follows:

Hello
World
Python
bannerAds