How to write a text file in Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
In Python you will often need to write text files to save anything that you might reuse in the future.
Writing a text file is as simple as reading it.
Just as reminder, I wrote an article about how to read a text file in Python.
Writing the file
# We define our text content to be written in the file.
text_content = """Lorem ipsum dolor it samet
Some text on a different line
"""
# We use open to open an instance of the file
with open("path/to/file.txt", "w") as file:
file.write(text_content) # We write all the text content into the file
See the "w" where we tell python in which mode it should deal with the file.
Modes can be create/read/write or even append.
Here we have "w" which tells Python to write the file.
If the file is not created it will create it then write the text_content.
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚