Short answer
If you're adding content to the ini file, use the r+
mode in the open()
function, instead of the w
mode.
with open(ini_path, "r+") as file:
file.write(ini_content)
Otherwise look for "method 2" below.
Long answer
A great answer is provided for this question on why a permission error is raised when trying to call the function open(some_path, 'w')
on files with a hidden (H) or system (S) attribute. You can experiment it by manually creating a new hidden file, and then using open(hidden_file_path, 'w')
; it will raise the same error.
When looking around about the more general case of hidden files, you can find answers of people suggesting to temporarily remove the hidden attribute, overwrite the file, and then add the attribute back.
import os
os.system(f"attrib -h {hidden_file_path}") # remove the "hidden" attribute
with open(hidden_file_path, 'w') as file:
file.write(new_content) # overwrite the file
os.system(f"attrib +h {hidden_file_path}") # add back the "hidden" attribute
This can be unsafe if for any reason you don't control the declaration of the hidden_file_path
variable (see "OS command injection"). Also, if you try to use it for overwriting a desktop.ini
file, it won't work. Further inspection with the attrib
command (os.system(f"attrib {hidden_file_path}")
in python, or directly from the command line) reveals that, as expected, these files have both hidden and system attributes (SH). That means that the previous approach should consider both attributes simultaneously.
# method 1
import os
os.system(f"attrib -h -s {ini_path}")
with open(ini_path, 'w') as file:
file.write(new_content)
os.system(f"attrib +h +s {ini_path}")
Alternatively, a cleaner option is just using the r+
mode instead of w
when calling open()
. It has worked for me so far when adding stuff to desktop.ini
files.
# method 2
with open(ini_path, "r+") as file:
file.write(ini_content)
Quick note: this approach overwrites completely the file only if the amount of characters in the previous content is less or equal than the amount of characters on the new content. For example, if the file's content is 12345
and you want to write abc
, the updated file will contain abc45
; whereas if you write abcdefg
, the updated file will contain abcdefg
.
So, if you're planning to update your ini file with, for example, a shorter path for your iconresource, maybe it's better to use method 1.
Tested using python 3.10.5