I'm trying to change iconresource on desktop.ini file after changing folder icon with this python script but I got this:
Exception has occurred: PermissionError [Errno 13] Permission denied: 'desktop.ini'
I've tried run as administrator, disabling UAC, and changing security permissions of file but no answer.
import configparser
config = configparser.ConfigParser()
config.read('desktop.ini')
pieces = config['.ShellClassInfo']['iconresource'].split('\\')
del pieces[:-1]
config['.ShellClassInfo']['iconresource'] = pieces[0]
with open('desktop.ini','w') as configfile:
config.write(configfile)
Exception has occurred: PermissionError [Errno 13] Permission denied: 'desktop.ini'
Short answer
If you're adding content to the ini file, use the
r+mode in theopen()function, instead of thewmode.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 usingopen(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.
This can be unsafe if for any reason you don't control the declaration of the
hidden_file_pathvariable (see "OS command injection"). Also, if you try to use it for overwriting adesktop.inifile, it won't work. Further inspection with theattribcommand (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.Alternatively, a cleaner option is just using the
r+mode instead ofwwhen callingopen(). It has worked for me so far when adding stuff todesktop.inifiles.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
12345and you want to writeabc, the updated file will containabc45; whereas if you writeabcdefg, the updated file will containabcdefg.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