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.
- 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.
- In this example, we use a
try
–except
block to catch theFileExistsError
exception that is raised if the file already exists. - We use the
open()
function with the exclusive creation mode ('x'
) to create a new file named'new_file.txt'
. - If the file already exists, the
open()
function will raise aFileExistsError
exception, which we catch in theexcept
block and print a message saying that the file already exists. - 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. - 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.
- 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