EN
Python - create file
0 points
In this article, we would like to show you how to create a file using Python.
Quick solution:
xxxxxxxxxx
1
file = open("example.txt", "x")
xxxxxxxxxx
1
file = open("example.txt", "w")
xxxxxxxxxx
1
file = open("example.txt", "a")
There are three parameters that we can use with open()
method to create a file:
x
- create - creates a file, returns an error if the file exist,w
- write - creates a file if the specified file does not exist,a
- append - creates a file if the specified file does not exist.
In this example, we create a file using open()
method with x
(create) parameter.
xxxxxxxxxx
1
file = open("example.txt", "x")
Output when the file doesn't exist:
xxxxxxxxxx
1
Process finished with exit code 0


Output when the file already existed:
xxxxxxxxxx
1
Process finished with exit code 1

In this example, we create a file using open()
method with w
and a
parameters.
xxxxxxxxxx
1
file = open("example.txt", "w")
or
xxxxxxxxxx
1
file = open("example.txt", "a")
Output when the file doesn't exist:


Output when the file already existed:
xxxxxxxxxx
1
Process finished with exit code 0