Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
897 views
in Technique[技术] by (71.8m points)

operating system - How to determine drive in Windows using Python?

I have string named C:/, and I want to detect if this string is path of drive.

Apparently, it seems to be drive, but I want a code or module that determines this is a drive.

I tried os.path.isdrive but there was no function like that.

I think answer is very simple one, but I don't know how to do this.

I'm using Python 3.8 and Window. Thanks.

question from:https://stackoverflow.com/questions/65641091/how-to-determine-drive-in-windows-using-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use the path.exists() function:

from os import path
path.exists("C:/")

If you want to test only for root directory of a drive ("C:/" and not "C:/File/File2/") you could check that by mesuring the lenght of the path:

def is_drive(path):
   if len(path) <= 3 and os.path.exists(path):
      return True
   return False

This method will return if drive exists. I hope this helps, it really depends on what you want to use this function for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...