While I understand os.access()
can be used to check if an existing file can be read or written, I was wondering whether a similar method can be used to see whether a file can be created.
I need to create a file at some point in my code, after several operations have been performed. However, at this time, it would be a shame if the file fails to be created (e.g. if I caught an exception at the time I use the open()
method), since the operations are complete. It would be much easier to check if creating the file will work, without creating it yet (i.e., is the name valid? does the program have access to the folder?...).
Of course, I could already create and open the file much earlier in my code, but I thought it best to avoid it:
- I would have to keep try and with blocks open for the most part of my program
- the file is used only by a function which is called at the end of my program (writing a report), so it would have to be passed as a parameter rather than being handled entirely within the function itself, from creation to closure.
does the program have access to the folder?
- if you know how to check permissions for a file, you know how to do it for a directory.rwx
in case of directories is read the content (list of files), write content (create new file) and enter the directory. You only need w. Also, useos.path.isdir()
to check whether your path is correct.Of course, I could already create and open the file much earlier in my code
- you can also create the file and close it (empty), and later reopen it as eitherw
ora
(although when it's empty,a
is not needed).