Hello

I wondered if anyone had an idea on a piece of code that could tell me the available free disk space.

There is a trick here, otherwise this easy question wouldn't be here.
I need the free disk space to read off where the program is being run, and NOT a particular drive letter.

EG
If i'm running the program from D drive, can i get the program to say in output

Current Drive : D
Size: 100gb
Free: 5gb

but if i run it from a USB stick
Current Drive: F
Size: 8000mb
Free: 500mb

I could try a dos command for freespace but you need to specify a drive letter to get an answer.

Anyone know of a solution or a piece of code that could work here?

Appreicate any help, while this is NOT critical to my program, it would be a bonus, so no stress :)

Ivan

You can get a drive letter from a path like this

import os
drive = os.path.splitdrive(mypath)[0]
print(drive)

Now for mypath, you could use either the current working dir os.getcwd() or your module's file path __file__ . Then you can call the dos command using subprocess.Popen (I normally work on linux, so I don't know your dos command for free space).

commented: Smart. +0

If you have Windows you can use this ...

# get disk information on Windows
# using the win32 extension module from:
# http://sourceforge.net/projects/pywin32/files/
# tested on Windows XP with Python25 and Python31

import win32file

def get_drivestats(drive):
    '''
    drive for instance 'C'
    returns total_space, free_space, used_space
    '''
    drive = drive.rstrip(':\\').rstrip(':/')
    sectPerCluster, bytesPerSector, freeClusters, totalClusters = \
        win32file.GetDiskFreeSpace(drive + ":\\")
    r = (
        (totalClusters*sectPerCluster*bytesPerSector),
        (freeClusters*sectPerCluster*bytesPerSector),
        ((totalClusters-freeClusters )*sectPerCluster*bytesPerSector)
        )
    return r

# pick a drive letter
drive = 'C'
total_space, free_space, used_space = get_drivestats(drive)

print("""
total_space = %d bytes
free_space = %d bytes
used_space = %d bytes""" % (total_space, free_space, used_space))

If you have Windows you can use this ...

# get disk information on Windows
# using the win32 extension module from:
# http://sourceforge.net/projects/pywin32/files/
# tested on Windows XP with Python25 and Python31

import win32file

def get_drivestats(drive):
    '''
    drive for instance 'C'
    returns total_space, free_space, used_space
    '''
    drive = drive.rstrip(':\\').rstrip(':/')
    sectPerCluster, bytesPerSector, freeClusters, totalClusters = \
        win32file.GetDiskFreeSpace(drive + ":\\")
    r = (
        (totalClusters*sectPerCluster*bytesPerSector),
        (freeClusters*sectPerCluster*bytesPerSector),
        ((totalClusters-freeClusters )*sectPerCluster*bytesPerSector)
        )
    return r

# pick a drive letter
drive = 'C'
total_space, free_space, used_space = get_drivestats(drive)

print("""
total_space = %d bytes
free_space = %d bytes
used_space = %d bytes""" % (total_space, free_space, used_space))

You should write a code snippet with this.

I was going to work through the first reply and then i saw the second reply which certainly looks like a complete piece of code and i could cut and paste, but i found an issue.

It appears you specifiy in the code which drive you want the free space info from, which is nice, but i want it from the current drive the program is running from, and that can change from computer to computer. The program doesn't "install" so it could be run from any location. But i want to gather disk info from that location, which appears more in the first solution, just opened up and bout to have a play.

I'll keep an eye out and thanks so far, see how we go hey.

OK, though alot of work lies ahead to get this implemented into my own program, i think i got this working by merging of the two answers, so instead of using
drive = 'C'
i used
drive = os.path.spltdrive(os.getvdw())[0]

Wondering, the answer given is in bytes which is a HUGE number even for a small 160gb drive and hate the see if i run this from my 1.5tb drive ... so what would i need to do to change the output to say rounded megabytes (1601mb), or even gb with a decimal point or two(160.01gb).

Would love to pursue this further, but will list this as solved as you have both successfully answered the question

Thankyou both.

Wondering, the answer given is in bytes which is a HUGE number even for a small 160gb drive and hate the see if i run this from my 1.5tb drive ... so what would i need to do to change the output to say rounded megabytes (1601mb),

Use this calculation
1024Bytes = 1Kilobyte
1024x1024Bytes = 1Megabyte
1024x1024x1024Bytes = 1Gigabyte
and so on...

or even gb with a decimal point or two(160.01gb).
Thankyou both.

use

print "The Free Disk Space is %.2f" %(my_decimal_value_of_space, )

As well as the bytes to MB/GB conversion, i have one other issue ... damn i tried this myself but it appears i'll have to really embarass myself, try to remember, one program i've ever made and i'm back after 6 months and for some reason, the easy things seem hard LOL

OK .. so the output of this program outputs to the interpreter, but i want the output to appear in my main window

i have to type snippets of code from another computer.

My main window has
space1 = Label(root, text = 'Total')
space2 = Label(root, text = 'total_space = %d bytes')

So the second line is the issue (and yeah i have the labels being placed elsewhere in the code) but the issue here is obvious, instead of giving me the answer in bytes, it simply prints what i typed

So my output says in my window
Total
total_space = %d

instead of
Total
16000000 bytes

I think i would like this to be a single item too, not space 1 and space2, will a /n work once i get the correct output?

Thankyou.

Mhh... I forgot TKinter at the time I dicovered wxPython. I haven't even written single GUI program in TkInter. So I guess I can't be of great help here. But In wxPy there is method called SetValue you will have a label and then Call its setvalue to set its display value. I guess TkInter have something simiral

Yeah my knowledge doesn't yet extend that far, infact took me an hour to work out your last reply, although in the end i used the /1024/1024 in the calculations instead of the print command for a cleaner looking output statement.

eg
(totalClusters*sectPerCluster*bytesPerSector/1024/1024),
Good thinking i thought :)

I actually moved the text to a more convient output window that is already in use and setup but i have the same issue

outputWindow.insert('15.0','Size of Drive: (total_space) MB\n')

The (total_space) has had many different attempts to get the actual number in there, but i'm not sure how, it just continues to output whatever i type.. bugger.

But almost there.

check this
and specifically this
Put final result of size to your lablel
Not TkInter expert though

How Weird .. it was google that bought me here.

I wasn't happy with that link, i dislike people who do that, i do google, but knowing what to google in this case was the issue, and even with your clever reply, i didn't see the answer to my problem.

I hope others won't be discouraged to help :(

I don't understand. Why don't you use

'Size of Drive: %d MB\n' % total_space

or (py >= 2.6)

'Size of Drive: {v} MB\n'.format(v = total_space)

to create the output message ?

I didn't do that cause i didn't know how. I'm still learning, there's alot to learn and i apoliguise, i only just completed uni for the year and i'm putting as many hours i can between earning some dollars.

I will try these new lines of code a little later tonight when i get a chance ...

Thankyou.

How Weird .. it was google that bought me here.

I wasn't happy with that link, i dislike people who do that, i do google, but knowing what to google in this case was the issue, and even with your clever reply, i didn't see the answer to my problem.

:(

Hi Ivan,
didn't I said that I don't know anything about TkInter? What else could I do than searching something that is near to what I thought you need?

If It was wxPython I would help alot, but I don't know anything about TkIntering. Anyway what did specifically choke you you? Didin't I show you what I specifically thought is the best from the links google provided????

ok ok ... sorry mate .. yeah you have tried to help, but i didn't see it as a 'tkinter' issue ... just an moving of output issue which i couldnt' define with the correct 3 to 4 words.

Anyways, the above didn't work(both attempts) as now i get told that total_space is not defined
So my line looks like this
outputWindow.insert('15.0','Size of Drive: {v} MB\n'.format(v = total_space)

I'm guessing the original code i used from vegaseat needs to be adjusted to work for this type of output?

and hey .. if it helps, i'll google, but not sure on the search terms.

Use your brain, instead of total_space put the name of the variable which contains the result!

ok ok ... sorry mate .. yeah you have tried to help, but i didn't see it as a 'tkinter' issue ... just an moving of output issue which i couldnt' define with the correct 3 to 4 words.

Its ok, but control your temper. you might end kicking your IDE ;)

but but .. you just insulted me again ... i guess i'm the one needing help so i have to eat the humble pie *sigh*

Well i've been using my brain (what the hell was i doing before that to get my program up and running??) but i can't solve it .... anything i try just tells me that it cannot be defined.
I kinda would love to see what you have for the answer, you obviously know cause your hinting at me to work it out, but i'm searching my code andthe answer isn't appearing and anything i have tried has been giving me the same error.

So out with it :D, tell me what it is, i'll try it and i'll congratulate you OR ... maybe your wrong and you can eat the humble pie :)

If you change your idea and use wxPython, I will be glad to help you from the ground up. Many here are wxPythoners ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.