Home » Python

Python File writelines() Method with Example

Python File writelines() Method: Here, we are going to learn about the writelines() method, how to write a list of strings to the file in Python?
Submitted by IncludeHelp, on December 24, 2019

File writelines() Method

writelines() method is an inbuilt method in Python, it is used to write a list of strings (multiple strings/items of a list) to the file.

Syntax:

    file_object.writelines(list)

Parameter(s):

  • list – It represents a list of string/text to write in the file.

Return value:

The return type of this method is <class 'NoneType'>, it returns nothing.

Example:

# Python File writelines() Method with Example

# creating a file
myfile1 = open("hello1.txt", "w")

# writing list of the strings
myfile1.writelines(["Hello, how are you?","I am fine.\n"])

# declare a list of strings
str_list = ["Shivang ","Prem ","David ","Linda "]
# writing list of the strings
myfile1.writelines(str_list)

# closing the file
myfile1.close()

# reading the file and printing text
myfile1 = open("hello1.txt", "r")
print(myfile1.read())
# closing the file
myfile1.close()

Output

Hello, how are you?I am fine.
Shivang Prem David Linda


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.