- Python writelines() Method [Practical Examples]
- Getting started with Python writelines and write method
- What is a file in Python?
- How to open and read a file in Python
- Syntax of Python writelines and write method
- Write specific text to the file
- Use Python writelines() to write specific text to the file
- Use Python write() method to write specific text to the file
- Write iterable to the file
- Use Python writelines() to write an iterable to the file
- Use Python write() method to write an iterable to the file
- Summary
- Further Reading
- Leave a Comment Cancel reply
- Python Tutorial
- How to Write Line to File in Python
- Example 1: How to write a line to a file
- How to write multiple lines to a file in Python
- Syntax of writelines()
- Parameters
- Example
Python writelines() Method [Practical Examples]
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.
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())
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))
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:
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:
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())
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())
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())
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())
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())
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
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Leave a Comment Cancel reply
Python Tutorial
- Python Multiline Comments
- Python Line Continuation
- Python Data Types
- Python Numbers
- Python List
- Python Tuple
- Python Set
- Python Dictionary
- Python Nested Dictionary
- Python List Comprehension
- Python List vs Set vs Tuple vs Dictionary
- Python if else
- Python for loop
- Python while loop
- Python try except
- Python try catch
- Python switch case
- Python Ternary Operator
- Python pass statement
- Python break statement
- Python continue statement
- Python pass Vs break Vs continue statement
- Python function
- Python call function
- Python argparse
- Python *args and **kwargs
- Python lambda function
- Python Anonymous Function
- Python optional arguments
- Python return multiple values
- Python print variable
- Python global variable
- Python copy
- Python counter
- Python datetime
- Python logging
- Python requests
- Python struct
- Python subprocess
- Python pwd
- Python UUID
- Python read CSV
- Python write to file
- Python delete file
- Python any() function
- Python casefold() function
- Python ceil() function
- Python enumerate() function
- Python filter() function
- Python floor() function
- Python len() function
- Python input() function
- Python map() function
- Python pop() function
- Python pow() function
- Python range() function
- Python reversed() function
- Python round() function
- Python sort() function
- Python strip() function
- Python super() function
- Python zip function
- Python class method
- Python os.path.join() method
- Python set.add() method
- Python set.intersection() method
- Python set.difference() method
- Python string.startswith() method
- Python static method
- Python writelines() method
- Python exit() method
- Python list.extend() method
- Python append() vs extend() in list
- Create your first Python Web App
- Flask Templates with Jinja2
- Flask with Gunicorn and Nginx
- Flask SQLAlchemy
How to Write Line to File in Python
To write a line to a file in Python, you can use the “with statement” along with the “open()” function in write mode (‘w’). The with statement helps you to close the file without explicitly closing it. This is the correct way to write a line to the file. The with statement is used to wrap the execution of a block with methods defined by a context manager.
Example 1: How to write a line to a file
If the file does not exist, the open() function will create a new file. If the file exists and you want to append the new content, then while creating a file, use the “a” mode. Use the “w” to write with truncation.
with open('data.txt', 'a') as f: f.write('Welcome Playstation 5\n')
It will create a new file called data.txt with the following content.
Alternatively, you can use the print() function instead of the write() function.
with open('data.txt', 'a') as f: print("hey there", file=f)
It will create a new file called data.txt with the following content.
The write() function is more efficient than the print() function. So my recommendation is to use the write() function to write the lines in the file.
How to write multiple lines to a file in Python
To write multiple lines to a file in Python, you can use the “with open()” expression and then the writelines() function. The writelines() method writes the items of a list to the file. The texts will be inserted depending on the file mode and stream position.
Syntax of writelines()
Parameters
Example
with open('data.txt', 'a') as f: line1 = "PS5 Restock India \n" line2 = "Xbox Series X Restock India \n" line3 = "Nintendo Switch Restock India" f.writelines([line1, line2, line3])
The output will be a data.txt file with the following content.
PS5 Restock India Xbox Series X Restock India Nintendo Switch Restock India
As you can see that we wrote three lines in a newly created file.