How to Write a String to a Text File using Python
In this tutorial, you will save a string as text file using Python.
TLDR solution
string2txt.py
# create a new file, if file does not exist. Do nothing, if file exists.
with open("target-path/file_name.txt", "x") as file:
file.write("a string")
# create a new file - overwrites if the file already exists
with open("target-path/file_name.txt", "w") as file:
file.write("a string")
# read and append to an existing file
with open("path-to-file/file_name.txt", "a") as file:
file.write(" additional text")
Example 1: Create a New Text File
Let's say, you want to save the string "Hello" as helloworld.txt on your desktop, where no file other text file with that name exists.
The following code achieves that:
string2txt.py
import os
desktop_path = os.path.expanduser("~/Desktop")
with open(desktop_path + "/helloworld.txt", "x") as file:
file.write("Hello")
Example 2: Overwrite a Text File
Suppose, you already have a file called helloworld.txt on your desktop.
The following code overwrites it:
string2txt.py
import os
desktop_path = os.path.expanduser("~/Desktop")
with open(desktop_path + "/helloworld.txt", "w") as file:
file.write("Hello")
Example 3: Read a Text File and Add Text
Suppose, you already have a file called helloworld.txt on your desktop, which holds the string "Hello".
The following code appends the string " World!" to that file:
string2txt.py
import os
desktop_path = os.path.expanduser("~/Desktop")
with open(desktop_path + "/helloworld.txt", "a") as file:
file.write(" World!")
Example 4: Create a Text File From a List of Strings
Now if you write a list of strings to a text file, use a for loop and append a newline character to each string:
string2txt.py
import os
desktop_path = os.path.expanduser("~/Desktop")
string_list = ['Hello', 'World!']
with open(desktop_path + "/helloworld.txt", "w") as file:
for string in string_list:
file.write(string + '\n')
That's it! You just learned how to create a text file in Python.