EN
Python - write text to file
0 points
In this article, we would like to show you how to write text to file in Python.
Quick solution:
xxxxxxxxxx
1
file = open("example.txt", "a")
2
file.write(" some text to append at the end.")
3
file.close()
In this example, we add some text at the end of the text file using open()
function with append parameter ("a"
).
xxxxxxxxxx
1
file = open("example.txt", "a")
2
file.write(" some text to append at the end.")
3
file.close()
or if the file isn't directly in our project folder:
xxxxxxxxxx
1
file = open("C:\\some_path\\example.txt", "a")
2
file.write(" some text to append at the end.")
3
file.close()
In this example, we overwrite the text file using open()
function with write parameter ("w"
).
xxxxxxxxxx
1
file = open("example.txt", "w")
2
file.write("New example.txt content.")
3
file.close()
or if the file isn't directly in our project folder:
xxxxxxxxxx
1
file = open("C:\\some_path\\example.txt", "w")
2
file.write("New example.txt content.")
3
file.close()