如何构建一个内存中的虚拟文件系统,然后将这个结构写入磁盘

How to construct an in-memory virtual file system and then write this structure to disk

我正在寻找一种在 Python 中创建虚拟文件系统的方法,以便在将这些目录和文件写入磁盘之前创建目录和文件。

使用 PyFilesystem 我可以使用以下内容构建内存文件系统:

>>> import fs
>>> dir = fs.open_fs('mem://')
>>> dir.makedirs('fruit')
SubFS(MemoryFS(), '/fruit')
>>> dir.makedirs('vegetables')
SubFS(MemoryFS(), '/vegetables')
>>> with dir.open('fruit/apple.txt', 'w') as apple: apple.write('braeburn')
... 
8
>>> dir.tree()
├── fruit
│   └── apple.txt
└── vegetables

理想情况下,我希望能够执行以下操作:

dir.write_to_disk('<base path>')

将此结构写入磁盘,其中 <base path> 是将在其中创建此结构的父目录。

据我所知,PyFilesystem 无法实现这一点。有没有其他我可以使用的东西,或者我必须自己实现吗?

如果您只想在内存中暂存文件系统树,请查看 tarfile module

创建文件和目录有点复杂:

tarblob = io.BytesIO()
tar = tarfile.TarFile(mode="w", fileobj=tarblob)
dirinfo = tarfile.TarInfo("directory")
dirinfo.mode = 0o755
dirinfo.type = tarfile.DIRTYPE
tar.addfile(dirinfo, None)

filedata = io.BytesIO(b"Hello, world!\n")
fileinfo = tarfile.TarInfo("directory/file")
fileinfo.size = len(filedata.getbuffer())
tar.addfile(fileinfo, filedata)
tar.close()

但是您可以使用 TarFile.extractall:

创建文件系统层次结构
tarblob.seek(0) # Rewind to the beginning of the buffer.
tar = tarfile.TarFile(mode="r", fileobj=tarblob)
tar.extractall()

您可以使用 fs.copy.copy_fs() to copy from one filesystem to another, or fs.move.move_fs() 来完全移动文件系统。

鉴于 PyFilesystem 还对底层系统文件系统进行了抽象 - OSFS - in fact, it's the default protocol, all you need is to copy your in-memory filesystem (MemoryFS),实际上,您会将其写入磁盘:

import fs
import fs.copy

mem_fs = fs.open_fs('mem://')
mem_fs.makedirs('fruit')
mem_fs.makedirs('vegetables')
with mem_fs.open('fruit/apple.txt', 'w') as apple:
    apple.write('braeburn')

# write to the CWD for testing...
with fs.open_fs(".") as os_fs:  # use a custom path if you want, i.e. osfs://<base_path>
    fs.copy.copy_fs(mem_fs, os_fs)