Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, open for writing if exists, otherwise raise error

Is there an option I can pass open() that will cause an IOerror when trying to write a nonexistent file? I am using python to read and write block devices via symlinks, and if the link is missing I want to raise an error rather than create a regular file. I know I could add a check to see if the file exists and manually raise the error, but would prefer to use something built-in if it exists.

Current code looks like this:

device = open(device_path, 'wb', 0)
device.write(data)
device.close()
like image 572
abferm Avatar asked May 29 '15 16:05

abferm


People also ask

Under what conditions can you fail to open a file for writing Python?

Python may fail to retrieve a file, if you have written the wrong spelling of the filename, or the file does not exist. We handle this situation by applying the try-except block. Since Python can not find the file, we are opening it creates an exception that is the FileNotFoundError exception.

What is a good way to handle exceptions when trying to write a file in Python?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

What happens if you open a file that does not exist in Python?

When we use a+ it opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.


1 Answers

Yes.

open(path, 'r+b')

Specifying the "r" option means the file must exist and you can read. Specifying "+" means you can write and that you will be positioned at the end. https://docs.python.org/3/library/functions.html?#open

like image 156
Ariakenom Avatar answered Oct 03 '22 06:10

Ariakenom