python-3.x 如何构造内存中的虚拟文件系统,然后将此结构写入磁盘

brc7rcf0  于 4个月前  发布在  Python
关注(0)|答案(2)|浏览(81)

我正在寻找一种方法来创建一个虚拟文件系统在Python中创建目录和文件,然后将这些目录和文件写入磁盘。
使用PyFilesystem,我可以使用以下内容构建内存文件系统:

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

字符串
理想情况下,我希望能够做到这样的事情:

temp_dir.write_to_disk('<base path>')


将此结构写入磁盘,其中<base path>是将在其中创建此结构的父目录。
据我所知,PyFilesktop没有办法实现这一点。有没有其他东西可以代替,或者我必须自己实现它?

kyks70gy

kyks70gy1#

您可以使用fs.copy.copy_fs()从一个文件系统复制到另一个文件系统,或者使用fs.move.move_fs()移动整个文件系统。
考虑到PyFilesystem还抽象了底层系统文件系统-OSFS-事实上,这是默认协议,您所需要的就是将内存中的文件系统(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)

字符串

3lxsmp7m

3lxsmp7m2#

如果您只想在内存中暂存文件系统树,请查看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()

相关问题