nathanhi / pyfatfs

Python based FAT12/FAT16/FAT32 implementation with VFAT support
https://pypi.org/project/pyfatfs/
MIT License
31 stars 14 forks source link

Create filesystem if it does not exist and 'create' flag is set in open_fs #15

Open nb-programmer opened 3 years ago

nb-programmer commented 3 years ago

open_fs function takes in the create optional argument, which when set, will create the filesystem instead raising an exception on opening a (non-existent) disk image file. Currently, pyfatfs does not make use of this argument and raises a pyfatfs._exceptions.PyFATException when opening a .img file.

For example:

>>> import fs
>>> fatfile = fs.opener.open_fs('fat://test.img', create=True) 
Traceback (most recent call last):
  File "C:\Users\[removed]\AppData\Local\Programs\Python\Python39\lib\site-packages\pyfatfs\PyFat.py", line 241, in open
    self.__set_fp(open(filename, mode=mode))
FileNotFoundError: [Errno 2] No such file or directory: 'test.img'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\[removed]\AppData\Local\Programs\Python\Python39\lib\site-packages\fs\opener\registry.py", line 229, in open_fs
    _fs, _path = self.open(
  File "C:\Users\[removed]\AppData\Local\Programs\Python\Python39\lib\site-packages\fs\opener\registry.py", line 186, in open
    open_fs = opener.open_fs(fs_url, parse_result, writeable, create, cwd)
  File "C:\Users\[removed]\AppData\Local\Programs\Python\Python39\lib\site-packages\pyfatfs\PyFatFSOpener.py", line 36, in open_fs
    fs = PyFatFS(filename=parse_result.resource,
  File "C:\Users\[removed]\AppData\Local\Programs\Python\Python39\lib\site-packages\pyfatfs\PyFatFS.py", line 53, in __init__
    self.fs.open(filename, read_only=read_only)
  File "C:\Users\[removed]\AppData\Local\Programs\Python\Python39\lib\site-packages\pyfatfs\PyFat.py", line 243, in open
    raise PyFATException(f"Cannot open given file \'{filename}\'.",
pyfatfs._exceptions.PyFATException: Cannot open given file 'test.img'.

But for a different file, it works as expected:

>>> zipfile = fs.opener.open_fs('zip://test.zip', create=True)
>>> print(zipfile) 
<zipfs-write 'test.zip'>

So an option to create a blank filesystem would be nice

nathanhi commented 2 years ago

I agree, adding mkfs support is desirable and is indeed planned for 1.0. Not too sure if a simple create=True will be enough though due to the vast amount of configuration options a FAT fs has. For now, only a dedicated mkfs function is planned but I will consider it once we have working mkfs code.