Search code examples
pythonunit-testingcross-platformtemporary-filesramdisk

How can I create a ramdisk in Python?


I want to create a ramdisk in Python. I want to be able to do this in a cross-platform way, so it'll work on Windows XP-to-7, Mac, and Linux. I want to be able to read/write to the ramdisk like it's a normal drive, preferably with a drive letter/path.

The reason I want this is to write tests for a script that creates a directory with a certain structure. I want to create the directory completely in the ramdisk so I'll be sure it would be completely deleted after the tests are over. I considered using Python's tempfile, but if the test will be stopped in the middle the directory might not be deleted. I want to be completely sure it's deleted even if someone pulls the plug on the computer in the middle of a test.


Solution

  • How about PyFilesystem?

    https://docs.pyfilesystem.org/en/latest/reference/memoryfs.html

    https://docs.pyfilesystem.org/en/latest/reference/tempfs.html

    The downside is that you have to access the filesystem with PyFilesystem API, but you can also access the real fs with PyFilesystem.