Languages
[Edit]
EN

Python - write text to file

0 points
Created by:
Haris65
536

In this article, we would like to show you how to write text to file in Python.

Quick solution:

file = open("example.txt", "a")
file.write(" some text to append at the end.")
file.close()

 

Practical examples

1. Append at the end of the file

In this example, we add some text at the end of the text file using open() function with append parameter ("a").

file = open("example.txt", "a")
file.write(" some text to append at the end.")
file.close()

or if the file isn't directly in our project folder:

file = open("C:\\some_path\\example.txt", "a")
file.write(" some text to append at the end.")
file.close()

2. Overwrite file content

In this example, we overwrite the text file using open() function with write parameter ("w").

file = open("example.txt", "w")
file.write("New example.txt content.")
file.close()

or if the file isn't directly in our project folder:

file = open("C:\\some_path\\example.txt", "w")
file.write("New example.txt content.")
file.close()
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Python - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join