Access to a file within a subfolder in APPDATA directory

31 Views Asked by At

I'm trying to open an XML file located within a subfolder the APPDATA dircetory. Obviously the folder changes depending on which user is logged in:

I have no issue if specify the name of the user, for example:

\\C:\Users\USER\AppData\Roaming\Folder1\Folder2\File.xml

However I wish to eliminate the "C:\Users\USER\Appdata\Roaming" part and swap it with this:

\\C:APPDATA\Folder1\Folder2\File.xml

Here is the error I receive:

OSError: Error reading file '\\C:APPDATA\Folder1\Folder2\File.xml': failed to load external entity "//Folder1\Folder2\File.xml"
1

There are 1 best solutions below

0
Mark Tolonen On

A couple of ways:

import os
from pathlib import Path

option1 = fr'{os.environ['appdata']}\Folder1\Folder2\File.xml'
option2 = Path(os.environ['appdata']) / r'Folder1\Folder2\File.xml'
print(option1)
print(option2)

Output:

C:\Users\xxx\AppData\Roaming\Folder1\Folder2\File.xml
C:\Users\xxx\AppData\Roaming\Folder1\Folder2\File.xml