How to know where is windows installed with Python?

Viewed 32

I am writing a program that needs to know which Drive is Windows drive . because I need to go to "Windows-Drive:\Users\publick\Desktop", I need some code or module that will give me the windows drive. Thanks for your kindness.

3 Answers

If what you really want is the drive where Windows is installed, use

import os
windows_drive = os.environ['SystemDrive']

But it looks like what you actually need is the public desktop folder. You can get that easier and more reliably like this:

import os
desktop_folder = os.path.join(os.environ['PUBLIC'], 'Desktop')

For the current user's desktop folder instead, you can use this:

import os
desktop_folder = os.path.join(os.environ['USERPROFILE'], 'Desktop')

But I'm not sure that the desktop folder is always called 'Desktop' and that it's always a subdirectory of the profile folder.

There is a more reliable way using the pywin32 package (https://github.com/mhammond/pywin32), but it obviously only works if you install that package:

import win32comext.shell.shell as shell
public_desktop_folder = shell.SHGetKnownFolderPath(shell.FOLDERID_PublicDesktop)
user_desktop_folder = shell.SHGetKnownFolderPath(shell.FOLDERID_Desktop)

(Unfortunately pywin32 is not exactly well documented. It's mostly a matter of first figuring out how to do things using Microsoft's Win32 API, then figuring out where to find the function within pywin32.)

#!/usr/bin/env python3


# Python program to explain os.system() method 
      
# importing os module 
import os 
  
# Command to execute
# Using Windows OS command
cmd = 'echo %WINDIR%'
  
# Using os.system() method
os.system(cmd)        # check if returns the directory [var = os.system(cmd) print(var) ] in Linux it doesnt

# Using os.popen() method
return_value = os.popen(cmd).read()

can you check this approach ? I am not on Win

I found my Answer!

`import os

Windows-Drive=os.path.dirname(os.path.dirname(os.path.join(os.path.join(os.environ['USERPROFILE']))))

This code is answer!

Related