In this Python tutorial, you will learn how to write a string to a text file using the file object’s write() method. The examples cover creating a file, overwriting existing content, appending text, writing multiple lines, and selecting an encoding.
Write a String to a Text File in Python
To write a string to a text file in Python, open the file in a suitable text mode and call write() on the returned file object. Pass the string that you want to store as the argument.
with open("file.txt", "w", encoding="utf-8") as file:
file.write("Text to write")
The with statement is the preferred way to work with files because it closes the file automatically, including when an exception occurs inside the block.
Steps to Write Python String Data to a File
- Call
open()with the path of the text file. - Select
"w"mode to create or overwrite the file, or"a"mode to append text. - Specify an encoding such as
encoding="utf-8"when the file may contain Unicode text. - Call
write()and pass a string. - Close the file, or use a
withstatement so that Python closes it automatically.
Python File Modes Used for Writing Text
| Mode | Behavior | When to use it |
|---|---|---|
"w" | Creates a file or replaces all content in an existing file. | Use when the new string should become the complete file content. |
"a" | Creates a file if necessary and writes new content at the end. | Use when existing text must be preserved. |
"x" | Creates a new file and raises FileExistsError if it already exists. | Use when accidentally overwriting an existing file must be prevented. |
"r+" | Opens an existing file for both reading and writing without automatically truncating it. | Use when you need controlled updates at a particular file position. |
Text mode is used by default, so "w" and "wt" have the same meaning. The examples below use the shorter form.
Python Examples for Writing Strings to Text Files
1. Write a String to a New Text File
The following program opens D:/data.txt in write mode and stores one string in it. If the file does not exist, Python creates it.
Python Program
#open text file
text_file = open("D:/data.txt", "w")
#write string to file
text_file.write('Python Tutorial by TutorialKart.')
#close file
text_file.close()
Reference tutorial for the program
After the program runs, data.txt contains the following text.
Python Tutorial by TutorialKart.
2. Check the Number of Characters Written by write()
The write() method returns the number of characters written to a text file. Store the return value when the program needs to confirm the length of the completed write operation.
Python Program
#open text file
text_file = open("D:/data.txt", "w")
#write string to file
n = text_file.write('Python Tutorial by TutorialKart.')
#close file
text_file.close()
print(n)
Output
32
The result is 32 because the supplied string contains 32 characters. In text mode, this return value represents characters rather than the number of encoded bytes stored on disk.
3. Write a String Using the with Statement
The following version performs the same operation with a context manager. Python closes the file when execution leaves the with block, so an explicit call to close() is unnecessary.
message = "Python Tutorial by TutorialKart."
with open("D:/data.txt", "w", encoding="utf-8") as text_file:
text_file.write(message)
Use a valid path for the operating system on which the program runs. For example, a relative path such as data.txt writes the file in the program’s current working directory.
4. Overwrite a String in an Existing Text File
Opening an existing file in "w" mode truncates it before the new string is written. This means all previous content is removed.
For instance, the earlier examples created a file and wrote text to it. Running the following program replaces that content with Hello World!.
Python Program
#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()
The existing file is overwritten by the new content.
Hello World!
5. Append a String Without Deleting Existing File Content
Open the file in append mode, "a", when the new string should be added after its existing content. Append mode creates the file if it does not already exist.
with open("D:/data.txt", "a", encoding="utf-8") as text_file:
text_file.write("\nThis line is appended.")
The newline character \n starts the appended string on a new line. The write() method does not insert a line break automatically.
6. Write Multiple Strings on Separate Lines
Call write() more than once when the strings are produced separately. Include \n wherever a new line is required.
with open("D:/data.txt", "w", encoding="utf-8") as text_file:
text_file.write("First line\n")
text_file.write("Second line\n")
text_file.write("Third line")
File content
First line
Second line
Third line
7. Write a List of Strings with writelines()
Use writelines() to write an iterable of strings. The method does not add separators or newline characters, so each item must include its own \n when separate lines are expected.
lines = [
"Apple\n",
"Banana\n",
"Orange\n",
]
with open("D:/data.txt", "w", encoding="utf-8") as text_file:
text_file.writelines(lines)
File content
Apple
Banana
Orange
Write Unicode Strings with UTF-8 Encoding
Specify encoding="utf-8" when writing text that may contain non-ASCII characters. Declaring the encoding also makes file behavior more consistent across operating systems.
message = "Hello, नमस्ते, こんにちは"
with open("greeting.txt", "w", encoding="utf-8") as text_file:
text_file.write(message)
Use the same encoding when reading the file later.
with open("greeting.txt", "r", encoding="utf-8") as text_file:
content = text_file.read()
print(content)
Write Non-String Values to a Python Text File
The write() method expects a string in text mode. Convert integers, floating-point values, lists, and other objects to text before passing them to the method.
count = 25
price = 19.95
with open("values.txt", "w", encoding="utf-8") as text_file:
text_file.write(str(count))
text_file.write("\n")
text_file.write(f"{price:.2f}")
Passing an integer directly, as in text_file.write(25), raises a TypeError because the argument is not a string.
Handle File Writing Errors in Python
A write operation can fail because the directory does not exist, the program lacks permission, the path is invalid, or the storage device cannot accept more data. Catch OSError when the program needs to report file-system errors without terminating unexpectedly.
try:
with open("data.txt", "w", encoding="utf-8") as text_file:
text_file.write("Saved text")
except OSError as error:
print(f"Could not write the file: {error}")
Do not catch every exception without examining it. Handling OSError keeps the exception scope focused on file-system failures.
Common Problems When Writing Python Strings to Files
Existing Text Disappears After Writing
This happens when the file is opened in "w" mode. Use "a" mode when the existing content must remain in the file.
Strings Appear on the Same Line
The write() and writelines() methods do not add line breaks. Add \n between strings or join them with a newline before writing.
items = ["Red", "Green", "Blue"]
with open("colors.txt", "w", encoding="utf-8") as text_file:
text_file.write("\n".join(items))
FileNotFoundError Occurs While Writing
Write mode can create the file, but it cannot create missing parent directories. Confirm that every directory in the path exists before opening the file.
TypeError Says write() Requires a String
Convert the value with str(), an f-string, or an appropriate serialization method before writing it to a text file.
Python String-to-File Questions
Does Python write() create a text file?
Yes. Opening a path in "w", "a", or "x" mode can create the file. Its parent directory must already exist.
What is the difference between write() and writelines()?
write() accepts one string. writelines() accepts an iterable of strings. Neither method adds newline characters automatically.
How do I write a string without overwriting a file?
Open the file in append mode with open(path, "a"). The new string is then written after the existing content.
Why should encoding=”utf-8″ be specified?
It allows the program to handle a broad range of Unicode characters and avoids relying on a platform-dependent default encoding.
Python Text-File Writing Review Checklist
- Confirm that
"w"mode is intended before replacing an existing file. - Use
"a"mode when previous content must be preserved. - Prefer a
with open(...)block so the file is closed automatically. - Specify
encoding="utf-8"for predictable Unicode text handling. - Pass a string to
write(), converting non-string values first. - Add
\nexplicitly when separate lines are required. - Verify that the parent directory exists and that the program has permission to write there.
Summary of Writing Strings to Python Text Files
In this Python Tutorial, we learned how to write a string to a text file with write(). We also covered automatic file closing with with, overwrite and append modes, multiple-line output, UTF-8 encoding, non-string values, and common file-writing errors.
TutorialKart.com