How to Write in a Text File using Python?17 Mar 2025 | 6 min read Reading and writing to a file for storage or later use are common tasks in programming. Python has a number of ways to work with files, but we'll especially focus on writing to text files. Text files are used to store plain text data, and Python makes it simple for programmers to read and write data in text files. In this tutorial, we will explain how users can write in a text file using Python. Python has an inbuilt function to create, write or read the files. It can handle two types of files normal text files and binary files. The choice between these two depends on the data you are working on and the application's requirements.
Syntax to Open a File in Python: The open() function can accept various parameters. But the user has to focus on the first two:
For writing in a text file, the user will use the following mode:
Example: To show how a user can write in a text file using Python It is totally up to the user whether they want to add the text in the following line or not. Example 2: To show how to use the write() function for writing the list of texts in the text file Output: ![]() Both methods give the same result. Steps to Write in a Text File in Python:For writing in the text file using Python, the user has to follow the following steps: Step 1 - Open the File - To begin writing to a text file, we first need to open it using the in-built open() function, which takes two parameters: the file name (including the path if the file is not in the current directory) and the mode in which we want to open the file. In the case of writing to a text file, we can either use the mode 'w', which stands for write mode, or the mode 'a', which stands for append mode. If the file doesn't exist, Python will create a new file with the given name. The open() function will return a file object, and that file object will have two useful functions to write text in it:
The write() function is used for writing the string in the text file, and the writelines() function is used for writing the list of the string in the file at once. The writelines() function can also accept the iterable object. The user can also pass the tuple of strings, the set of strings, etc. To write in the next line, the user must manually add the new line character. Step 2 - Write to the file: As soon as the file is opened in write mode, we can either use the write() function or the writelines() function to write in it. The write() method takes a string as a parameter we want to write to the file. We can write multiple lines by calling the write() function multiple times or using newline characters (\n) between strings to separate the lines. Step 3 - Close the file: The user can close the text file using the close() function. After writing the desired content to the file, it's important to close it properly. Closing the file ensures that any changes are saved, and system resources are freed up. Example 2: To show how users can add a new line character in a txt file It is totally up to the users whether they want to add the text in the following line or not. Example 3: To show how to use the write() function for writing the list of texts or strings in a text file Output: ![]() Explanation: In the above example, we first created a list of strings named lines_1, and then we opened that file using the open() function with the 'with' statement. We then used a for-loop to iterate over the elements of the list, followed by writing the line and adding a new line character to the file. A new line character is added at the end of the for loop, and the pointer gets positioned at the next line. If the text.txt file does not exist in the folder, the open() function will create the new file, and the operations are performed accordingly. Example 4: To show how users can write the list of text strings in the text.txt file using writelines() function: Output: ![]() Explanation: In the above example, the writelines() function write each list element in a single line in the file. If the user treats each list element as a line, they have to link it with a new line character. Example 4: To show how a user can link the newline character with each element of the line in the text.txt file We have already seen in example number 3 how we can add a new line character after each list element. While using the writelines() function, we must add a new line character in the string. Output: ![]() Explanation: In the above example, the writelines() function writes the list element into the text.txt file, where each list element is ended with a new line character. ConclusionIn this tutorial, we have explained how a user can write texts in a text file using Python and its different functions. We first learned about normal and binary text files, followed by the syntax of how to open a file. We also looked over the difference between 'w' (write mode) and 'a' (append mode). We then learned about the steps to write in a text file in Python and implemented various examples to understand different methods to write in a text file. Next TopicPython KeyError |
The scipy.stats.lomax describes the Lomax continuous random variable. It is an instance of the rv_continuous class inherited from the generic methods. It completes the techniques by adding details specific to this distribution. The Probability Density Function, which gives the Lomax Distribution, is given by: The probability density function...
4 min read
Introduction Dual-pivot Quicksort is a sophisticated sorting algorithm that improves the original Quicksort technique. The main idea behind this approach is to efficiently segment the input array by using two pivot items rather than just one. The dual-pivot approach for various input data sets greatly enhances the...
4 min read
Python is a popular programming language for various tasks such as data analysis, web development, and machine learning. One of the reasons for its popularity is the vast number of libraries available to extend its functionality. These libraries, also known as modules, are pre-written code that...
4 min read
Structural Pattern Matching, also known as pattern matching or match statement, is a feature introduced in Python 3.10 that allows developers to write more expressive and concise code. This feature is inspired by similar constructs in other programming languages like Rust, F#, and Haskell. This article will...
7 min read
| Why Python doesn't support pointer In this tutorial, we will learn about pointer in Python and see why Python doesn't support pointer concepts. We will also understand how we can simulate the pointer in Python. Below is the introduction of the pointer for those who don't...
9 min read
Introduction Solving linear equations is a fundamental mathematical operation that Python makes simple. ax + by = c, where a, b, and c are constants, is how linear equations, or those with the highest power of 1, are represented. When solving a linear equation, the main objective...
3 min read
Python provides many built-in methods to handle the precision of floating points. In this tutorial, we will discuss the most common types of methods to set precision in Python. Most of the methods are defined under the math module. Various Methods to handle Precision The following methods come...
2 min read
Object Recognition is a technology that lies under the broader domain of Computer Vision. This technology is capable of identifying objects that exist in images and videos and tracking them. Object Recognition also known as Object Detection, has various applications like face recognition, vehicle recognition,...
5 min read
Python is a high-level programming language that is used extensively for data science, machine learning, and web development. One common operation in data science is to round floating values to two decimal places. This operation is useful when dealing with financial data or any other numeric...
3 min read
SFTP, abbreviated for SSH File Transfer Protocol and known as Secure File Transfer Protocol, is a network protocol that allows us to access files, transfer them and manage them over any dependable data stream. The program works on a secure channel, like SSH, that the...
7 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India