Skip to content

Python write string to file

  • by

Use the write() function on the text file object and pass the string as an argument to this write() function to write a string to file in Python.

To write a string to a Text File, follow these steps:

  1. Open the file in write mode using the open() function.
  2. Write a string to the file using the write() method.
  3. Close the file using the close() method.

For writing to a text file, you use one of the following modes:

'w'Open a text file for writing. If the file exists, the function will truncate all the contents as soon as you open it. If the file doesn’t exist, the function creates a new file.
'a'Open a text file for appending text. If the file exists, the function appends contents at the end of the file.
‘+’Open a text file for updating (both reading & writing).

Python writes a string to the file

Simple example code.

text_file = open("sample.txt", "w")



Python writes a string to the file

You can use the value returned by the write() function. write() function returns the number of bytes written to the file.

text_file = open("sample.txt", "w")

n = text_file.write('Hello')


Output: 5

Write to an Existing File

The new content overwrites the existing file.

#open text file
text_file = open("D:/data.txt", "w")
#write string to file
n = text_file.write('Hello World!')
#close file

Specify the path for the text file

Don’t forget to place ‘r‘ before your path name to avoid any errors in the path.

text_file = open(r'C:\Users\rohit\Desktop\Test\Example.txt', 'w')
my_string = 'This is a Test'

Do comment if you have any doubts or suggestions on this Python write file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.