Save a string as a txt file in Python

With the aid of a few Python example programs, we will learn how to write a String to a text file in this lesson.

Write a string to Text File in Python

To compose a string to a text file in Python, we can call the write() capability on the text document item and pass the string as a contention to this write() method.

Here is how to write a string in a text file step by step.

  • Utilize the open() method to open the text file in write mode. The function returns a file object.
  • Use the write() function of the file object and pass the string to it as an argument.
  • Once you’re done writing, use the close() function to close the file.

Add a String to a New Text File

Following the procedures outlined above, we’ll take a text constant in the example below and write the text to the text file.

Python program:

file = open("aman.txt", "w")
a = file.write('Hi, How are you all?')



Process finished with exit code 0

The number of letters that were recorded to the text document is returned by the write() function.

Keep in mind that if the text file is already there, this type of writing overwrites the contents. If the file already exists, the text is written to it before making a new one.

Write text  to the existing text file

If you want to add data, open the file in append mode first, and then use the file object’s write() function.

Python Code:

file = open("aman.txt", "a")
a = file.write('Aman')

So here it will append the string at the end of the word present in that document.

So these are the ways to save a string as a txt file in Python. I hope you like this article.


Leave a Reply

Your email address will not be published. Required fields are marked *