Python writelines() Method [Practical Examples]


Written by - Bashir Alam
Reviewed by - Deepak Prasad

 

Introduction to Python writelines and write method

A file is some information or data which stays in the computer storage devices. Python gives us easy ways to manipulate these files. We can open, read and write to these files using Python. In this tutorial, we will learn how we can write to file using the python writelines method and python write method.

First, we will learn how we can open and read a file in Python and then will discuss the simple syntax of python writelines and write method. We will also cover how we can write specific text, append text and write iterable text to file using Python writelines and Python write method by taking various examples. In a nutshell, this tutorial contains all the necessary information that you need to know in order to start working with Python writelines and Python write methods.

 

Getting started with Python writelines and write method

The Python file method writelines() writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value of the Python writelines method. And the same is with the python write method.  The write() method writes a specified text to the file. The text will be inserted at the current file stream position, default at the end of the file. In this section, we will discuss what is a file in Python, how to open a file, and then will see the syntax of Python writelines and Python write methods.

 

What is a file in Python?

As we already discussed that a file is a container in a computer system for storing information. Files used in computers are similar in features to that of paper documents used in library and office files. There are different types of files such as text files, data files, directory files, binary and graphic files, and these different types of files store different types of information. In this tutorial, will consider text file type. Let us say we have the following file stored in our system which contains the following data.

Python writelines file

In the upcoming sections, we will use the same file and write to it using the python writelines and write method.

 

How to open and read a file in Python

There are different ways to open a file in Python. In this tutorial, we will be using a built-in function open() to open the file. Then we will use different methods to read the opened file. See the following simple example.

# opening a file in Python
File = open('myfile.txt')
# reading file in Python
print(File.read())

Output:

You are
Welcomed to
Go linux cloud

The read() method reads all the data that is stored inside our file.  The read() method also takes an optional argument, which specifies the number of characters to be read. For example, see the following python program.

# opening a file in Python
File = open('myfile.txt')
# reading file in Python
print(File.read(20))

Output:

You are
Welcomed to

Notice that this time the read method only reads the first 20 characters as specified in the argument.

 

Syntax of Python writelines and write method

Before going into the syntax of Python writelines and write method, we need to learn about file mode. The writelines method writes data to file depending on the mode.  If the file mode is"a", then the texts will be inserted at the current file stream position, default at the end of the file. And if the file mode is"w", then the file will be emptied before the texts will be inserted at the current file stream position, default 0. We specify the file mode while opening the file using open() method. See the syntax below:

file = open("myfile.txt', 'a')
file = open(myfile.txt', 'w')

Now let have a look at python writelines method syntax. See the example below:

file.writelines(list)

The writelines method takes a list of strings or bytes as an argument and appends it to the file depending on the file mode specified earlier. The syntax of the python write method is similar to the writelines method. See the example below:

file.write(byte)

The write method takes text or byte object as an argument and appends it to the file.

 

Write specific text to the file

The write() method expects a string as an argument and writes it to the file. If we provide a list of strings, it will raise an exception. The writelines() method expects an iterable argument. Also, the write() method displays the output but does not provide a new line character, whereas the writelines() method displays the output and provides a new line character at the end of the string.

It is important to note that writelines() do not automatically insert a new line after each item in the iterable. We have to provide a new line by ourselves. If we have many lines to write to a file, writelines() could be a better option. It performs well because it doesn’t create a temporary concatenated string, just iterating over the lines.

 

Use Python writelines() to write specific text to the file

Now, let us take an example and see how we can write a specific text to the file using the writelines() method. See the example below:

# variables
line1 = "This"
line2 = "is"
line3 = "GolinuxCloud"
lines = line1, line2, line3
# opening the file in write mode
with open('myfile.txt', 'w') as file:
    # python writelines method
    file.writelines(lines)
# open file to read
f = open('myfile.txt')
# printing the appended data
print(f.read())

Output:

ThisisGolinuxCloud

Notice that the writelines appended the text without any extra line. To append data in separate lines, we have to specify the extra line explicitly. See the same example with text in each line below:

# variables
newline = '\n'
line1 = "This"
line2 = "is"
line3 = "GolinuxCloud"
lines = line1,newline, line2, newline, line3
# opening the file in write mode
with open('myfile.txt', 'w') as file:
    # python writelines method
    file.writelines(lines)
# open file to read
f = open('myfile.txt')
# printing the appended data
print(f.read())

Output:

This
is
GolinuxCloud

Notice that we have specified a new variable for a new line which just prints a new line.

 

Use Python write() method to write specific text to the file

Now let us append the same text to the file using the python write() method. See the example below:

# variables
newline = '\n'
line1 = "This"
line2 = "is"
line3 = "GolinuxCloud"
lines = line1 + newline + line2 + newline + line3
# opening the file in write mode
with open('myfile.txt', 'w') as file:
    # python write method
    file.write(lines)
# open file to read
f = open('myfile.txt')
# printing the appended data
print(f.read())

Output:

This
is
GolinuxCloud

Notice that we have concatenated the lines to one text and provided as one text to the write method because it cannot take iterables as an argument.

 

Write iterable to the file

The join() method takes all items in an iterable and joins them into one string. In this section, we will take a list of strings and then concatenate the elements of the list using the join() method and will pass as an argument to the write() and writelines() method.

 

Use Python writelines() to write an iterable to the file

Now, let us take an example and see how we can use the Python writelines method to write an iterable to the file. See the example below:

# List contains strings
mylist = ['this ', 'is ', 'GolinuxCloud']
# opening the file in writing mode
with open('myfile.txt', 'w') as f:
    # python writelines method and join method
    f.writelines('\n'.join(mylist))
# opening file to read
myfile = open('myfile.txt')
# read file
print(myfile.read())

Output:

this
is
GolinuxCloud

So the join method joins the elements of the list and we passed it as an argument to the writelines method.

 

Use Python write() method to write an iterable to the file

Now let us take the same example but this time we will use the python write() method instead of writelines() method. See the example below:

# List contains strings
mylist = ['this ', 'is ', 'GolinuxCloud']
# opening the file in writing mode
with open('myfile.txt', 'w') as f:
    # python write method and join method
    f.write('\n'.join(mylist))
# opening file to read
myfile = open('myfile.txt')
# read file
print(myfile.read())

Output:

this
is
GolinuxCloud

Notice that the write method has appended the concatenated text to the file.

 

Summary

A file is some information or data which stays in the computer storage devices. In this tutorial, we learned how we can append text to the file using a python programming language. First, we learned how we can open a file and read the file in Python. We discussed the two different kinds of mode; "a" and "w" mode. Then we learned about the syntax of the python writelines() and Python write() method.

At the same time, we discussed how we can use the Python writelines() and Python write() method to write a specific text to the file by using various examples. Furthermore, we also discussed how we can append an iterable to the file using the Python writelines() and python write() method. In a nutshell, this tutorial contains all the necessary details and methods that are used to append and write to Python files.

 

Further Reading

Python writelines method
Python write method
Python file handling 

 

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models. You can reach out to him on his Linkedin or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment

X