1

I've noticed that when I set the "hidden file" file attribute to true for a text file such as test.json, then when I open the file in python 3.5 it returns the following error:

>>> h = open('test.json','w')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
PermissionError: [Errno 13] Permission denied: 'test.json'

But I'm still able to read the file just fine:

>>> h = open('test.json','r')
>>> for line in h:
...    print (line)
...
{"send_key": "Return, Enter", ... }

Any idea why this is? Do I need to do something like run as admin, or clear this attribute, write the file, and set the attribute again?

Some other questions that I found while trying to see if this was asked already didn't help that I could see:

How to remove read-only attrib directory with Python in Windows?
open() is not working for hidden files python https://sanjaymadnani.wordpress.com/2015/06/06/hide-and-denied-access-folder/

Thanks, Justin

Eradicatore
  • 1,501
  • 2
  • 20
  • 38
  • 2
    Try opening with r+ instead of w. This question might be answered here : https://stackoverflow.com/questions/13215716/ioerror-errno-13-permission-denied-when-trying-to-open-hidden-file-in-w-mod https://stackoverflow.com/questions/13215716/ioerror-errno-13-permission-denied-when-trying-to-open-hidden-file-in-w-mod – MattWBP Oct 05 '17 at 18:56
  • Ok, thanks! That worked. I also read up on the various options here just now: https://stackoverflow.com/questions/1466000/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r – Eradicatore Oct 05 '17 at 19:09
  • 1
    As mentioned in the linked duplicate, this problem is due to the `O_CREAT` [`_wopen`](https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx) mode used for "w" mode in Python 3, which corresponds to WinAPI `CREATE_ALWAYS`. A workaround would be to use `open(os.open('test.json', os.O_WRONLY | os.O_TRUNC), 'w')`, which corresponds to an `OPEN_EXISTING` disposition, but works similarly in terms of truncating and using write-only mode. – Eryk Sun Oct 05 '17 at 19:14
  • Ok, so I've since realized that I do have an additional question. Using mode 'w' also trucates the file to zero. I tried w+ but it also fails with the permissions issue. So is there a way with r+ to still overwrite parts of the file? – Eradicatore Oct 05 '17 at 20:22
  • 1
    That's what I did in the example with `os.open`, to get exactly the same write-only mode (not read-write) and truncate the file to 0 bytes. – Eryk Sun Oct 05 '17 at 20:26
  • 2
    Apparently I got the corresponding `CreateFile` disposition wrong. I thought the C runtime's `_wopen` used `OPEN_EXISTING` and then truncated the file manually. But I just checked in the debugger and see that `O_TRUNC` simply uses `TRUNCATE_EXISTING` to have Windows truncate the file. – Eryk Sun Oct 05 '17 at 20:38

0 Answers0