In order to perform file operations such as creating, reading, and writing Text File In Python, it has built-in functions.
Python is capable of dealing with two types of files in particular: plain text files and binary files, to name a couple.
Throughout this tutorial, we’ll be looking at how to write content into text files using the Python programming language.
How To Write To A File In Python
To write to a text file in Python, you must first complete the steps outlined below.
- Opening the file for writing requires the use of the open() method, which must be passed a filepath as a parameter to the function.
- Second, we must write to the file, which can be accomplished through the use of several built-in methods such as write(), and writelines().
- After completing the write operation, the text file must be closed using the close() function.
Now that we’ve seen how to write to a text file, let’s break down each of these methods before diving into examples.
How Does Python open() Work?
If the file is openable, the open() function returns the corresponding file object.
open(file, mode='w', buffering=-1, encoding='None, errors=None, newline=None, closefd=True, opener=None) Where, file = path-like object representing the file path mode = This is optional Parameter. It is a string that specifies the mode in which the file should be opened.
There are numerous parameters to the open() function. Let’s look at the parameters required for writing to a text file. It opens the file in the mode you specify and returns a file object.
|‘r’||Open a file for reading mode (default if the mode is not specified)|
|‘w’||Open a file for writing. Python will create a new file if does not exist or truncates a file content if the file exists|
|‘x’||Create an exclusive file by opening a file.|
|‘a’||Open a file to append the text to. If the file does not exist, it is created.|
|‘t’||Open a file in text mode. (default)|
|‘b’||Open a file in binary mode.|
|‘+’||Open a file for updating (reading and writing)|
Methods For Writing Text In A File In Python
In order to write data into a text file, there are two options.
- write(): writing a line to a text file is accomplished using the write() function. It only inserts a single line into the text file in question.
- writelines(): writing multiple string lines at once to a text file is accomplished using the
writelines()method accepts an iterable object, such as a list, set, tuple, or another similar type of collection.
Python close() Function Usage
In order to close a file, use the close() function on the file. Performing this operation after data has been written to the file is a requirement and it is a best practice because it frees up the memory space used by that file. There may be an unhandled exception if this happens.
To ensure that the file is properly closed after the write operation is complete, we can make use of the “with” statement. Specifying an explicit close method every time is unnecessary.
Writing Text Files Code Examples
Let us see a series of code examples to read, write, and write lines at once in a file using Python.
Write and Read Text To File Using write()
The following code demonstrates how to use the
write() function to write a list of texts to a text file:
#Initializing A List of String To write listToWrite = ["You Are Visiting", "Coduber.com", "Daily."] with open("demoFile.txt", 'w') as openFile: #Writing Item From The List To The File for line in listToWrite: openFile.write(line) #Adding a New Line openFile.write("\n")
Use the open function with the ‘r’ mode to open the file in reading mode and read it line by line. Let’s take a look at some code to see how you can do that.
#If you Want To Read A File with open("demoFile.txt", 'r') as openFile: fileContent = openFile.read() print(fileContent) openFile.close()
You Are Visiting Coduber.com Daily.
Append Lines To Text File And Read The Appended Lines From A Text File
You must first open the text file in the append mode and then perform the write() operation, as shown in the example below if you want to append the line to an existing text file.
#Open the File In the Append Mode with open("demoFile.txt", 'a') as openFile: lineToAppend = "You are Learning Python Here." openFile.write(lineToAppend) openFile.close()
Let’s read the appended line as well as the rest of the file to ensure that the code above successfully appended the line to the text file.
#Open the File In the Append Mode with open("demoFile.txt", 'r') as openFile: #In This Example We Will Read the File #Line by Line for line in openFile.readlines(): print(line) openFile.close()
You Are Visiting Coduber.com Daily. You are Learning Python Here.
Write Text To File Using writelines() In Python
The writelines() method can be used to write multiple lines into a text file. There is no limit to the number of lines that can be written using the writelines() method.
How to write a list in Python? Let’s look at an example.
#Initializing A List of String To write listToWrite = ["You Are Visiting", "\nCoduber.com", "Daily."] with open("demoFile.txt", 'w') as openFile: #Writing Item From The List To The File openFile.writelines(listToWrite) openFile.close()
As seen in the preceding image, the lines were added to the text file all at once using writelines().
Append Text To File Using writelines() In Python
Open the text file in append mode and perform the writelines() operation as shown below if you want to append multiple lines to the file.
#Initializing the String to Append textToAppend = "\nThis Line is Append as Example." #Opening the file in Append Mode with open("demoFile.txt", 'a') as openFile: #Writing Item From The List To The File openFile.writelines(textToAppend) openFile.close()
Writing To UTF-8 Text File
If you use the code from the previous examples to write UTF-8 characters to a text file, you’ll get an error like this:
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-44: character maps to <undefined>
You must pass the encoding=’utf-8′ parameter to the open() function in order to open a file and write UTF-8 characters to it. The following example demonstrates how to write UTF-8 characters into a text file:
#Initializing the String to Write in UTF-8 utfTextToWrite = "これは別の言語です。" #Opening the file in Append Mode with open("demoFile.txt", 'w', encoding='utf-8') as openFile: #Writing Item From The List To The File openFile.write(utfTextToWrite)
If you want to append text to a text file, use the open() function in a mode; otherwise, open the file in w mode.
When you’re finished with a file, use the close() method to close it, or the with statement when you first open it.
Use the write() and writelines() functions to write to a text file. To write UTF-8 characters into a file, use the open() function with the encoding=’utf-8′ argument.
If you’re still having trouble writing text to a file in Python, please let me know in the comments and I’ll get back to you as soon as possible.