如何构造一个内存虚拟文件系统,并将其写入dis

2024-09-26 22:12:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法,在将这些目录和文件写入磁盘之前,用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

理想情况下,我希望能够做一些类似的事情:

^{pr2}$

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

据我所知,PyFilesystem无法实现这一点。还有什么可以替代的吗?或者我必须自己去实现吗?在


Tags: 文件方法目录txtapplediropenfs
2条回答

如果您只想在内存中暂存一个文件系统树,请查看(tarfile模块)[https://docs.python.org/3/library/tarfile.html]。在

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

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创建文件系统层次结构:

^{pr2}$

您可以使用^{}从一个文件系统复制到另一个文件系统,或者使用^{}来移动文件系统。在

考虑到PyFilesystem还抽象了底层系统文件系统^{}-事实上,这是默认协议,您只需将内存中的文件系统(^{})复制到该文件系统,实际上,您将把它写入磁盘:

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)

相关问题 更多 >

    热门问题