Windows get all disk python

how to get a list of available drives (partitions) in windows

is there some python standard or ‘Python for Windows Extensions’
functionality to iterate or list-return the available drives (‘A:’,
‘B:’, ‘C:’, . ) on a machine running windows?

from os import *
from os.path import *

for i in range(ord(‘a’), ord(‘z’)+1):
drive = chr(i)

is there some python standard or ‘Python for Windows Extensions’
functionality to iterate or list-return the available drives (‘A:’,
‘B:’, ‘C:’, . ) on a machine running windows?

is there some python standard or ‘Python for Windows Extensions’
functionality to iterate or list-return the available drives (‘A:’,
‘B:’, ‘C:’, . ) on a machine running windows?

seemed to be a problem that’s not easy to be googled.

and sorry in advance for the double-post which will show up soon.

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

Your message for python-help@python.org, the Python programming language assistance line, has been received and is being delivered. This automated response is sent to those of you new to.

here’s another interesting algorithmic exercise, again from part of a larger program in the previous series. Here’s the original Perl documentation: =pod merge($pairings) takes a list of.

Hi, I’d like to get drives and partitions (and their size too) with python under Linux. So far, I thought of reading /proc/partitions but maybe i could use fdsik also ? How would I do that in.

I’m formatting my mirrored drives and installing a third drive for raid 5 to add more space. I have backup exec. Can anyone tell me the best way to backup SQL so I can be sure it will restore.

Hello, I would like to know if anyone as found a way to list a image next to a list box to indicate what type of drive (local or network) and a folder I would like to present in a user.

Hi all, I am new to the list and I didn’t want to seem rude at all so I wanted to ask if this was okay first. I have a program I have written in perl which uses a postgresSQL database as the.

Does .NET have a wrapper to list actual physical drive volumes on the local PC? My.Computer.Filesystem.Drives lists the partitions and volumes that have drive letters attached. I’m looking to.

Hey all! Another fast question! How can I get a list of all available hard disk partitions on the current computer! I managed to work out one my self but it works only with Windows! Any one.

Hi all How do I get the list of all physical disks attached to my computer, similar to what is displayed under Disk drives in Device Manager: 0: MAXTOR 6L040j2 1: ST3802110a Thank you

The next Access Europe meeting will be on Wednesday 5 July 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central.

Hello, I want to share a page https://opensource-heroes.com/ with a rating of open-source developers sorted by sum of stars of their projects. There are also numerous current projects featured on.

Step right up, brave innovators and fearless pioneers of the coding world! As you’re about to learn, JavaScript can now do so much more! The gates of web3 and beyond await. We’re excited to share a.

The issue you’re facing seems to be related to file locking and build configurations. To resolve it, try the following steps: Make sure that all instances of the IDE are closed before attempting.

1. Define a Clear Vision and Strategy Before embarking on a digital transformation journey, it’s crucial to have a clear vision of what you want to achieve and develop a comprehensive strategy.

I have a blank Access DB where I am adding a data source link to SharePoint. After I link I choose everything I want to bring over. However, when I do that I see all the items from the site with.

Hello, I am currently preparing for SQL interviews and came across a fantastic resource that provides a list of SQL query interview questions. While going through the questions, I stumbled upon a.

By using Bytes.com and it’s services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.

Источник

Список дисков и сетевых расположений в python [Windows]

Как я могу получить список всех дисков и сетевых расположений с Python под Windows 10? Список должен состоять из «Локальные диски», «Сетевые диски» и «Сетевые расположения».

Пример

TYP HD HD NETWORK LOCATION some_list = ["C:\\", "D:\\", "\\some.network.address\some_folder"] 

Мое решение:

Есть ли способ лучше решить проблему? Не думаю, что мой сокращенный синтаксический анализ — «хорошее» решение .

import win32api from os import getenv, listdir from os.path import join import win32com.client NETWORK_SHORTCUTS_FOLDER_PATH = getenv('APPDATA') + \ "\\Microsoft\\Windows\\Network Shortcuts" # Add Logical Drives drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] # Add Network Locations network_shortcuts = [join(NETWORK_SHORTCUTS_FOLDER_PATH, f) + "\\target.lnk" for f in listdir(NETWORK_SHORTCUTS_FOLDER_PATH)] shell = win32com.client.Dispatch("WScript.Shell") for network_shortcut in network_shortcuts: shortcut = shell.CreateShortCut(network_shortcut) drives.append(shortcut.Targetpath) print(drives) 

Сетевое расположение (не только сетевые диски!):

Я разбираю вывод net use . Грязно, но работает на всех окнах. — person Jean-François Fabre &nbsp schedule 25.05.2018

Эта сетевая папка представляет собой ярлык в% AppData% \ Microsoft \ Windows \ Network Shortcuts, который отображается в папке виртуального компьютера. Это не подключенный диск, который будет указан net use . — person Eryk Sun &nbsp schedule 26.05.2018

Вы можете использовать комбинацию PyWin32 и ctypes, чтобы получить IShellItem для FOLDERID_ComputerFolder . Привяжите его к IEnumShellItems , чтобы отобразить папку. Для каждого элемента проверьте, является ли это ссылкой через GetAttributes(SFGAO_LINK) . Если это так, получите целевой элемент оболочки, привязав к BHID_LinkTargetItem , а затем получите путь к файловой системе через GetDisplayName(SIGDN_FILESYSPATH) , который должен быть UNC-путем. — person Eryk Sun &nbsp schedule 26.05.2018

Я запутался. Вы предпочитаете, чтобы все работало так, как раньше? Или вам специально нужно переключиться с сетевых дисков на сетевые ярлыки (не из-за изменений ОС, а потому, что вы так выбрали)? Вопрос по этому поводу неясен. — person ivan_pozdeev &nbsp schedule 28.05.2018

@ivan_pozdeev Я обновил вопрос, чтобы прояснить свою проблему! — person clfaster &nbsp schedule 28.05.2018

os.path.join поддерживает произвольное количество аргументов. — person ivan_pozdeev &nbsp schedule 29.05.2018

Ответы (1)

    Не указывайте жестко путь к папке, а получите его с помощью GetKnownFolderPath . Эта функция не предоставляется pywin32 с v223 , но мы можем использовать более старые совместимые SHGetFolderPath :
from win32com.shell import shell,shellcon NETWORK_SHORTCUTS_FOLDER_PATH = shell.SHGetFolderPath(0,shellcon.CSIDL_NETHOOD,None,0) 

Привет, спасибо за ответ, я этого не знал! Но проблема остается, на моем ноутбуке сетевое местоположение добавляется ИТ-отделом, поэтому я не могу изменить метод, который они используют. Похоже, они просто добавляют сетевые расположения, а не сетевые диски (сейчас в Windows 10). Но все же приятно знать, что по идее ничего не изменилось;) — person clfaster; 28.05.2018

Для известных папок вы можете вызвать SHGetKnownFolderIDList через ctypes. Настройка там немного запутана для комментария. Затем преобразуйте адрес в PIDL через shell.AddressAsPIDL PyWin32. В остальном все просто. shell_item = shell.SHCreateShellItem(None, None, pidl); items = list(shell_item.BindToHandler(None, shell.BHID_EnumItems, shell.IID_IEnumShellItems)) . Затем, если item.GetAttributes(shellcon.SFGAO_LINK) , получите цель ссылки через link_item = item.BindToHandler(None, shell.BHID_LinkTargetItem, shell.IID_IShellItem); target_path = link_item.GetDisplayName(shellcon.SIGDN_FILESYSPATH) . — person Eryk Sun; 30.05.2018

Источник

Python-сообщество

[RSS Feed]

  • Начало
  • » Python для новичков
  • » Получит список всех дисков windows

#1 Дек. 16, 2012 13:45:01

Получит список всех дисков windows

кроме как проверки в цикле через os.listdir() каждой буквы нет стандартных способов?

#2 Дек. 16, 2012 16:46:11

Получит список всех дисков windows

В winAPI есть функция для этого.
Вот пример с SO:

import win32api drives = win32api.GetLogicalDriveStrings() drives = drives.split('\000')[:-1] print drives 

#3 Дек. 16, 2012 19:26:04

Получит список всех дисков windows

GaiveR
а стандартными способами никак?

#4 Дек. 16, 2012 21:24:16

Получит список всех дисков windows

import os letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' drives = [':'.format(d) for d in letters if os.path.exists(':'.format(d))] 

Источник

Cross platform way to list disk drives on Linux, Windows and Mac using Python?

There isn’t really a unified naming scheme for Linux devices that guarantees you a formatable block device. There are conventions, but they can vary widely and I can call my thumb-drive /Thomas/O if I want and there is no cross-platform way in Python to know:

  1. That /Thomas/O corresponds to /dev/sdf1
  2. That /dev/sdf1 can have a FAT32 filesystem made on it
  3. That /dev/sdf is not preferred to /dev/sdf1

I’m pretty sure that neither is there a cross-platform Python module which will allow you to determine that H:/ is formattable on a Windows system but that Z:/ is not.

Each system will require its own specific checks and validations which you could best learn from studying open-source disk manipulation software.

Solution 2

The psutil package (https://pypi.python.org/pypi/psutil) has a disk_partitions function.

>>> import psutil >>> psutil.disk_partitions() [sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='D:\\', mountpoint='D:\\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='E:\\', mountpoint='E:\\', fstype='', opts='cdrom'), sdiskpart(device='F:\\', mountpoint='F:\\', fstype='NTFS', opts='rw,fixed')] 
>>> import psutil >>> psutil.disk_partitions() [sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro'), sdiskpart(device='/dev/sr0', mountpoint='/media/VBOXADDITIONS_4.3.10_93012', fstype='iso9660', opts='ro,nosuid,nodev,uid=1000,gid=1000,iocharset=utf8,mode=0400,dmode=0500,uhelper=udisks')] 

Solution 3

I don’t see a way in psutil to include net mounts on Windows. I.e., \foobar\home is mapped to X:, but X: does not appear in the list returned by psutil.disk_partitions() (local drives are).

Update: To include net drives in the returned list, simply use:

Solution 4

Eric Smith’s answer to use psutil works well for me on Windows, but on OS X, I prefer this:

from os import listdir listdir('/Volumes') 

It gives you back the human readable names that, at least in my case, would be preferable (IE, it gives you Macintosh HD instead of / or /dev/disk0s2 .)

Источник

Русские Блоги

Конкурсная ссылка А. Игра трахается Ссылка на заголовок резюме Удивительная конвергенция, этот NM — удар сокращения размера Б. Кекс трахается Ссылка на заголовок резюме Найти правила снова . я табле.

Spring Boot Project git push giteee

Не создавайте readme.md, чтобы создать совершенно пустой проект при создании проекта на Gitee $ git init Инициализированный git $ git status $ git add . $ .

Механизм копирования при записи, чтобы понять

Во-первых, копирование на запись под Linux Прежде чем объяснить механизм копирования при записи в Linux, мы должны сначала знать две функции:fork()иexec(), Обратите внимание, чтоexec()Это не конкретна.

Python Learning — марина

Только поддерживает реализацию функций, таких как функции в Python, и содержание Pickle невидимо. При чтении необходимо исходное содержание Маринованное письмо: Чтение Pickle: Уведомлени.

1 Среда развертывания

Справочник статей 1 Ввести зависимости 1.1 Удаленный импорт 1.2 Местное введение 1 Ввести зависимости 1.1 Удаленный импорт 1.2 Местное введение.

Источник

Читайте также:  Php print новая строка
Оцените статью