我正在研究一个Python程序,它将在闪存驱动器上无休止地生成文本文件。每次程序想要创建和写入文件时,我都想检查是否有足够的存储空间来执行此操作。如果有,我想将文件写入闪存驱动器。如果没有足够的存储空间,我想对内容做些其他事情。做这个的最好方式是什么?例如:
def write_file(contents):
if "Check if there is sufficient storage space on E:\ drive.":
# Write to file.
file = open("filename", "w")
file.write(contents)
file.close()
else:
# Alternative method for dealing with content.
我需要有一个很好的方法来找到file.write()
将占用多少空间,并将其与驱动器上的可用空间进行比较。
这取决于平台;这是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.
你可以获得磁盘的信息,因为它解释了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()
现在,使用used
和available
来确定磁盘是否有足够的空间。