Changing a filename in a restricted directory (via script)

Somewhat OT here, but I was wondering if anyone knows how to rename a file in a restricted directory via Python script. The catch is that the file is in a subdirectory of C:\Program Files and to change anything in there you need to have administrator rights. Even logged in as administrator, when doing it manually, UAC still asks for confirmation. And in the following script it just fails…

direc='C:\Program Files\BlaBlaBla'


if os.path.isfile(orig_fpathname):
    os.rename(orig_fpathname, new_fpathname)

#should rename the file to ''

But this fails with a message “Windows error”. I assume that means “permission denied”…

I can’t put this file anywhere else on the computer either, it only works in that directory. I am just trying to deactivate the automatic loading by keeping the app which looks for it from finding the correct filename. But I also need to restore it later.

If anyone has any ideas…

Not sure if I’m reading your code correctly, but it seems as though you are defining direc as a directory in Program Files named BlaBlaBla and then joining it with a filename blabla.xyx.

Where is the backslash between the path and directory? Does os.path.join supply it automatically? (Too lazy to check myself :slight_smile:)

Yep, that’s its purpose…

The code is honestly a bit of pseudo code, the filenames have been changed to protect the innocent… :stuck_out_tongue_winking_eye:

I think you also should use raw strings when using backslashes, or escape them. \b is BELL I think.

I’ll try that and see if it helps, I was under the impression that os.path.join was specifically designed to grab simple strings and format them correctly for paths, but maybe I’m wrong about that.

I assumed as much. You really mean guilty, don’t you? :wink:

>>> c = 'c:\blabla'
>>> import os.path
>>> os.path.join(c, "halloo")
>>> c = r'c:\blabla'
>>> os.path.join(c, "halloo")

(On OSX, but shows that \b gets interpreted differently than \\b)

1 Like

Raw strings didn’t help, but I looked at the file in question and it’s not just the directory - even for admins, the file itself (it’s a .dll) only has read and run rights, but not modify… so I guess I’ll give up for now, it was just an experiment anyway… Thanks to all for responding!

Mitch, this is a pretty generic python question. You might have better luck getting a good answer on stackoverflow. I don’t have a decent answer for you and it will take a lot of effort to figure this out where someone on stackoverflow may know the answer right away.

OK, thanks Steve!