如何检测闪存驱动器上是否有足够的存储空间来写入文件?

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

我正在开发一个 Python 程序,可以在闪存驱动器上生成无限文本文件。这个程序将是唯一在那个闪存驱动器上运行的东西,我想在每次写入时检查是否有足够的存储空间space。

如果有,我想将文件写入驱动器。如果 space 不够,我想对内容做些别的。例如:

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.

我需要找到一个好方法来确定 space 一个 file.write() 操作将花费多少,并将其与驱动器上的空闲 space 进行比较。

谢谢!

您可以按照说明获取磁盘信息here:

import subprocess
df = subprocess.Popen(["df", "path/to/root/of/disk"], stdout=subprocess.PIPE)
output = df.communicate()[0]
device, size, used, available, percent, mountpoint = \
    output.split("\n")[1].split()

现在,使用 usedavailable 来决定磁盘是否有足够的空间 space。

这取决于平台;这是 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)

如果你在 Linux 我不确定,但我发现了这个:

from os import statvfs

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

您的函数应如下所示:

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.