How to Write in Text File using Python
In this tutorial, we will explain how the users can write in the text file using Python language.
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.
Example: (To show how the user can write in the text file using Python)
Steps Used for Writing in the Text File:
For writing in the text file using Python, the user has to follow the following steps:
Syntax: To open a file
The open() function can accept various parameters. But the user has to focus on the first two:
For writing in the text file, the user will use the following mode:
The open() function will return the file object, and the file object will have two useful functions to write text in the file:
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 the line in the text file, the user has to add the new line character manually.
Example 1: To show how the user can add the new line character in the Text.txt file
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
If the text.txt file does not exist in the folder, the open() function will create the new file.
Example 3: To show how the user can write the list of text strings in the text.txt file.
If the user treats each element of the list as the line, then they have to link it with the newline character.
Example 4: To show how the user can link the newline character with each element of the line in the text.txt file
In this tutorial, we have explained how the user can write the text in the text file using Python and its different functions.
JavaTpoint offers too many high quality services. Mail us on [email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected]
Duration: 1 week to 2 week