6

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.
6
  • 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, use os.path.isdir() to check whether your path is correct.
    – h4z3
    Jul 19, 2019 at 14:30
  • 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 either w or a (although when it's empty, a is not needed).
    – h4z3
    Jul 19, 2019 at 14:31
  • "I could already create and open the file much earlier in my code": that is no guarantee: the directory where the file is created (or even the whole file system/device) may not exist anymore by the time you actually want to use the file.
    – 9769953
    Jul 19, 2019 at 14:34
  • 1
    Since the file system can change under the hood while your program is running, the only way to really know whether the file can be created (and written to) at the actual point in the program, is to do that during the actual point in the program. Checking before, as stated in my other comment, provides no actual guarantee that the file can be created at a later time.
    – 9769953
    Jul 19, 2019 at 14:35
  • @h4z3: Permissions, even if unchanging, can lie—especially with NFS, but also with SELinux or so. Jul 19, 2019 at 16:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.