What Is Exclusive Creation In Python

Exclusive creation is a file mode in Python that allows a file to be created only if it does not already exist. In Python, exclusive creation mode is denoted by the character ‘x‘. If a file with the specified name already exists, attempting to open it in exclusive creation mode will result in a FileExistsError exception. This article will tell you how to use it with examples.

1. Python File Exclusive Creation Mode Examples.

  1. To open a file in exclusive creation mode in Python, you can use the open() function with the ‘x‘ mode. Here’s an example.
    >>> try:
    ...     with open('new_file.txt', 'x') as file:
    ...         file.write('This is a new file.')
    ...         print('File created successfully.')
    ... except FileExistsError:
    ...     print('File already exists.')
    ... 
    19
    File created successfully.
  2. In this example, we use a tryexcept block to catch the FileExistsError exception that is raised if the file already exists.
  3. We use the open() function with the exclusive creation mode ('x') to create a new file named 'new_file.txt'.
  4. If the file already exists, the open() function will raise a FileExistsError exception, which we catch in the except block and print a message saying that the file already exists.
  5. If the file does not exist, we write some text to it using the write() method and print a message saying that the file was created successfully.
  6. Note that if you run this code again, it will fail because the file already exists.
    >>> try:
    ...     with open('new_file.txt', 'x') as file:
    ...         file.write('This is a new file.')
    ...         print('File created successfully.')
    ... except FileExistsError:
    ...     print('File already exists.')
    ... 
    File already exists.
  7. Now you can open the newly created file and see it’s content using the below python code.
    >>> with open('./new_file.txt', 'r') as file:
    ...     file_content = file.read()
    ...     print(file_content)  
    ... 
    This is a new file.

References

  1. How To Read, Write, Append Binary Files In Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.