
The write() method writes a string to a text file.The open() function returns a file object that has two useful methods for writing text to the file: write() and writelines(). Open a text file for updating (both reading & writing).
If the file exists, the function append contents at the end of the file. If the file doesn’t exist, the function creates a new file. If the file exists, the function will truncate all the contents as soon as you open it.
The mode parameter specifies the mode for which you want to open the text file.įor writing to a text file, you use one of the following modes: Mode. The file parameter specifies the path to the text file that you want to open for writing. The open() function accepts many parameters. The following shows the basic syntax of the open() function: f = open(file, mode)
Third, close the file using the close() method. Second, write to the text file using the write() or writelines() method. First, open the text file for writing (or append) using the open() function. To write to a text file in Python, you follow these steps: The following illustrates how to write a string to a text file: with open( 'readme.txt', 'w') as f:į.write( 'readme') Code language: JavaScript ( javascript ) Steps for writing to text files Summary: in this tutorial, you’ll learn various ways to write text files in Python.