如何构造内存中的虚拟文件系统,然后将此结构写入磁盘 [英] How to construct an in-memory virtual file system and then write this structure to disk

查看:129
本文介绍了如何构造内存中的虚拟文件系统,然后将此结构写入磁盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a way to create a virtual file system in Python for creating directories and files, before writing these directories and files to disk.

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

Using PyFilesystem I can construct a memory filesystem using the following:

>>> 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

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

Ideally, I want to be able to do something like:

dir.write_to_disk('<base path>')

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

To write this structure to disk, where <base path> is the parent directory in which this structure will be created.

据我所知,PyFilesystem无法实现这一目标.还有什么我可以代替的,还是我必须自己实现?

As far as I can tell, PyFilesystem has no way of achieving this. Is there anything else I could use instead or would I have to implement this myself?

推荐答案

您可以使用

You can use fs.copy.copy_fs() to copy from one filesystem to another, or fs.move.move_fs() to move the filesystem altogether.

鉴于PyFilesystem还在基础系统文件系统周围进行了抽象- OSFS -实际上,这是默认协议,您只需要复制内存文件系统( MemoryFS ),实际上,您会将其写入磁盘:

Given that PyFilesystem also abstracts around the underlying system filesystem - OSFS - in fact, it's the default protocol, all you need is to copy your in-memory filesystem (MemoryFS) to it and, in effect, you'll have it written to the disk:

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)

这篇关于如何构造内存中的虚拟文件系统,然后将此结构写入磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆