Python 中是否有允许在单个文件中进行虚拟文件系统管理的库?

Is there a library in Python which allows virtual file system management in single file?

我正在做一个程序。我认为我不需要在这里展示它,但我想知道是否可以创建存储在单个文件上的虚拟文件系统。例如,我有一个名为 my_file_system.fs 的文件,有没有办法将虚拟文件系统创建到该单个文件中。基本上:

/home/xcodz/
    |
    +--myfilesystem.fs
       |
       +--testdir
       +--test.txt
       +--downloads
          |
          +--example1.txt

我基本上想要基本的文件系统界面。没有所有者、日期或其他元数据。 Zip 是一个好主意,但它只是一次读取系统中的整个文件,并且不提供类似文件的界面。所以我需要一个非常基本的单个文件文件系统,我可以在其中像普通 IO 对象一样使用文件。

编辑 存储在文件系统中的文件单个文件将高达 3 GB,而我没有那么大的 ram。 TarFiles 似乎并没有让我的工作变得更好

编辑 我的意思是说一些文件系统就像带有虚拟框的文件系统。

解决方案 #1 - TAR 文件

TAR 文件基本上是单个文件中的 unix 文件系统。您可以使用 tarfile.

在 python 中与他们合作

优点:

  • 开箱即用。
  • 具有 POSIX 文件系统的所有功能。
  • tarfile 为文件提供流 reader & writer API。

缺点:

  • 没有非POSIX 功能,例如加密或内存映射文件。
  • 无法就地编辑文件,您必须提取它们然后重新添加它们。

解决方案 #2 - 环回文件系统

如果您可以要求完成安装以便 运行 您的程序,您可以 use a loopback filesystem:

$ truncate -s 100M /tmp/loopback.ext4
$ mkfs -t ext4 /tmp/loopback.ext4
mke2fs 1.45.5 (07-Jan-2020)
Discarding device blocks: done                            
Creating filesystem with 25600 4k blocks and 25600 inodes

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (1024 blocks): done
Writing superblocks and filesystem accounting information: done

$ sudo mkdir /mnt/loop
$ sudo mount -o loop /tmp/loopback.ext4 /mnt/loop/
$ df -T /mnt/loop
Filesystem     Type  Size  Used Avail Use% Mounted on
/dev/loop11    ext4   93M   72K   86M   1% /mnt/loop
$ sudo tree /mnt/loop/
/mnt/loop/
└── lost+found

1 directory, 0 files

优点:

  • 像普通文件系统一样使用。
  • 可从 python 进程外部访问,离线和在线。
  • 非常容易调试。
  • 您可以添加加密、使用内存映射文件以及真实文件系统的任何其他功能。

缺点:

  • 需要 root。
  • 需要在 运行 启动您的进程之前安装。
  • 需要卸载(至少,以防崩溃)。
  • 必须预先设置大小,可以调整大小但并非微不足道。
  • Very difficult to support cross-platform.

解决方案 #3 - DYI 文件系统

由于您最关心文件 I/O,您可以使用 BytesIO. To support multiple files in a filesystem hierarchy, you can put those files in a trie. You need to serialize and deserialize all that, for which you can use pickle.

来实现它

优点:

  • 比基于 TAR 的解决方案更容易定制。
  • 可以做成一个库,而且很好用,可以重复使用。

缺点:

  • 您需要更多编码。
  • 每次都对整个数据结构进行 picking 是不可扩展的。
  • 如果您需要碰撞安全,则需要在每次(相关)修改 trie 或任何文件后进行 pickle。

选择什么

由于您的需求非常基本,请选择 #1 - TAR 个文件。

您可以使用 SVFS 包。

SVFS allows to create virtual filesystem inside file on real filesystem. It can be used to store multiple files inside single file (with directory structure). Unlike archives, SVFS allows to modify files in-place. SVFS files use file-like interface, so they can be used (pretty much) like regular Python file objects. Finally, it’s implemented in pure python and doesn’t use any 3rd party modules, so it should be very portable. Tests show write speed to be around 10-12 MB/s and read speed to be around 26-28 MB/s.