EN
Python - create file
0
points
In this article, we would like to show you how to create a file using Python.
Quick solution:
file = open("example.txt", "x")
file = open("example.txt", "w")
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.
Practical examples
Example 1
In this example, we create a file using open()
method with x
(create) parameter.
file = open("example.txt", "x")
Output when the file doesn't exist:
Process finished with exit code 0
Output when the file already existed:
Process finished with exit code 1
Example 2
In this example, we create a file using open()
method with w
and a
parameters.
file = open("example.txt", "w")
or
file = open("example.txt", "a")
Output when the file doesn't exist:
Output when the file already existed:
Process finished with exit code 0