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:
- Open the file in write mode using the open() function.
- Write a string to the file using the write() method.
- Close the file using the close() method.
For writing to a text file, you use one of the following modes:
Mode | Description |
---|---|
'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")
text_file.write('Hello')
text_file.close()
Output:
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')
text_file.close()
print(n)
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
text_file.close()
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' text_file.write(my_string) text_file.close()
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.