Search code examples
pythondiskspace

How can I detect if there is sufficient storage on a flash drive to write to a file?


I am working on a Python program that will make infinite text files on a flash drive. This program will be the only thing operating on that flash drive, and I want to check if there is sufficient storage space each time it writes.

If there is, I want to write the file to the drive. If there isn't enough space, I want to do something else with the contents. For example:

def write_file(contents):
    if "Check if there is sufficient storage space on E:\ drive.":
        with open("filename", "w") as file:
            file.write(contents)
    else:
        # Alternative method for dealing with content.

I need to have a good way to find how much space a file.write() operation will take and compare that with the free space on the drive.

Thank you!


Solution

  • This is platform dependent; here is the solution for Windows:

    import ctypes
    import platform
    
    def get_free_space(dirname):
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
        return free_bytes.value / 1024
    
    if __name__ == "__main__":
        free_space = get_free_space("path\\")
        print(free_space)
    

    If you are on Linux I'm not sure but I found this:

    from os import statvfs
    
    st = statvfs("path/")
    free_space = st.f_bavail * st.f_frsize / 1024
    

    Your function should look like so:

    def write_file(contents):
        if free_space >= len(contents.encode("utf-8")):
            # Write to file.
            file = open("filename", "w")
            file.write(contents)
            file.close()
        else:
            # Alternative method for dealing with content.