Skip to content

Python File writelines() Method

  • by

Python File writelines() Method writes the items of a list to the file. Using this method you can write a sequence of strings to the file.

fileObject.writelines( sequence )

The sequence can be any iterable object producing strings, typically a list of strings. This method does not return value.

Python File writelines() Method

A simple example code writes the content of a list to a file.

file1 = open("student.txt", "w")
lst = []

for i in range(3):
    name = input("Enter student names: ")
lst.append(name + '\n')

file1.writelines(lst)
file1.close()
print("Read file.")

Output:

Python File writelines() Method

Another Example

f = open(r'test.txt', 'w')

f.writelines(['foo', 'bar'])
f.close()

f = open(r'test.txt')
print(f.read())

Output: foobar

Do comment if you have any doubts or suggestions on this Python write file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading