How to Write in Text File using PythonIn 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 Output: 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. Output: 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 Output: ConclusionIn this tutorial, we have explained how the user can write the text in the text file using Python and its different functions. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263477.html