How to Write String to Text File in Python

In Python, string data structure is used to input those data enclosed in the single or double quotation marks. The string data collects any characters, including alphabets and numbers. Strings play an important role in daily programming tasks, either printing output or communicating with users. This Python guide will demonstrate the method to write the string to a new or the same existing text file in Python. The content topics of this post are as follows:

So, let’s get started!

How to Write String to Text File in Python?

In Python, writing a string to a text file is done by opening or creating the text file using the “open()” function. The “open()” function has the following syntax:

Syntax:

f = open(file, mode)

The open function’s first parameter takes the “file” name as an input value, and the second parameter indicates the mode function, which is to be performed on the text file. The following “mode” values can be used:

ModeDescription
‘a’This mode indicates that the text file is opened for appending new text to an existing file.
‘w’This mode indicates that the text file is opened for writing the new text.
‘+’This mode is used when both reading and writing will be performed on the file.
‘r’This mode indicates that the file is only read.

After opening the file according to “mode”,the next step is to write the text file. The “write()” function is used to write the string value inside the text file. The syntax of the “write()” function is shown below:

file.write(filename/byte)

The “byte” in the above syntax referred to binary data. To write binary data, we need to open the text file in binary mode rather than text mode.

Example 1: Writing String to New Text File

The “write()”function of Python is used to write the string value into a new or already created text file. In the example given below, the string is written into the text file:

Code:

file_text = open("F:\itslinuxfoss\Documents\itslinuxfoss.txt", "w")
file_text.write('Python Tutorial by itslinuxfoss.')
file_text.close()

In the above Python code:

  • The text file is created using a function named “open()” by specifying its path inside the parenthesis. The “path” is where we want to create and save our text file.
  • The “write()” function is used to write the string by taking the value of the string as an argument.
  • After writing the string, the text file must be closed in the program because if it is not closed, the string is not written in the text file.

Output:

Firstly, we go to our specific path where the text file is created; the below snippet shows the location of our text file path.

Open the text file:

After opening the text file, we can see that the string is written in our text file named “itslinuxfoss”.

Note: To overwrite this text file, the same code is used with a new string value.

Example 2: Appending New String in the Text File

Creating a new text file is not always mandatory. Sometimes we just need to append our new data to the existing content of the file. The string is appended into the text file by opening any file in the “append mode” denoted by “a”. In the following code,  new string is appended into the old text file:

Code:

str_data = '\nLearn Python Programming on itslinuxfoss'
with open("F:\itslinuxfoss\Documents\itslinuxfoss.txt", "a") as file: 
    file.write(str_data)

The following code state that:

  • The new string value is stored in the variable named “str_data”.
  • Using the “with” statement before the “open()” function opens the file. The “with” statement provides the functionality of not closing the file at the end because the with statement closes the file automatically after reading and writing.
  • The “path” of the already created file is input inside the parentheses of the “open()” function.
  • The second parameter of the “open()” function takes the value “a” which enables the appending mode of a text file.
  • The “write()” function takes the string value as an argument to append the text. The “write()” function must be placed with some indentation otherwise, it gives an error.

Output:

After appending the new string, the text file is opened by going to the specific path of a text file. The path of the text file is shown below:

The output shows that the new string line is appended to the text file.

Example 3: Writing Multiple Strings to a Text File

Multiple strings are written into the text file using the “list” data structure. Let’s insert multiple strings into the text file via the following code:

Code:

file_1 = open("F:\itslinuxfoss\Documents\itslinuxfoss.txt", "w")
list_str = ['Hello', 'welcome to itslinuxfoss', 'Python Guide']
for i in list_str:
    file_1.write(i + '\n')
file_1.close()

In the following code:

  • The “open()” function opened the file and stored it in the variable named “file_1”.
  • Multiple strings are initialized in the list variable named “list_str”.
  • The “for loop” iteration is performed on the list string.
  • The value of string elements are written to the text file one by one using the function named “write()”.
  • The second parameter takes the newline character “\n” as an input to add every string element in a new line of the text file.

Output:

After writing multiple strings, we go to our specific path where the text file is created; the below snippet shows the location of our text file path.

From the output, multiple strings are written to a text file named “itslinuxfoss”.

That’s all from this guide!

Conclusion

In Python, the “write()” function is used to write the string value in the text file. The new string value is written into a new text file or can be replaced with the string in the existing file. The multiple strings can also be written into the text file using a list data structure, and new strings are also appended at the end of the string using the append mode “a” of the “open()” function. This post has explained how to write strings to a text file in Python.