Languages
[Edit]
EN

Python - create file

0 points
Created by:
Mark-Rotteveel
537

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
Python - create file (before)
Python - create file (before)
Python - create file (after)
Python - create file (after)

Output when the file already existed:

Process finished with exit code 1
Python - create file - output when file already existed
Python - create file - output when file already existed

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:

Python - create file (before)
Python - create file (before)
Python - create file (after)
Python - create file (after)

Output when the file already existed:

Process finished with exit code 0
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