How to write a text file in Python

1 min readDataGetting Started
7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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.

How to read a text file in Python
How to read a text file using 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.

7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

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. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.