Tinche / aiofiles

File support for asyncio
Apache License 2.0
2.67k stars 149 forks source link

Asynchronously check file/folder exists #73

Open mirismaili opened 4 years ago

mirismaili commented 4 years ago

Hi, Thanks for the good library.

Can we check path existence asynchronously with this library? I mean something like this:

path_existence = await aiofiles.path.exists(some_path)

If not, I request this feature. Thanks again.

dangillet commented 3 years ago

I noticed that the implementation for exists is actually a call to os.stat and making sure it's not raising an exception.

    def exists(self):
        """
        Whether this path exists.
        """
        try:
            self.stat()
        except OSError as e:
            if not _ignore_error(e):
                raise
            return False
        except ValueError:
            # Non-encodable path
            return False
        return True

As os.stat is wrapped in aiofiles.os.stat, I think it would be rather straightforward to achieve that.

samuelcolvin commented 3 years ago

For anyone else coming to this, I'm using the following baed on @dangillet's observation above.

from pathlib import Path, _ignore_error as pathlib_ignore_error
from typing import Union

import aiofiles.os

async def path_exists(path: Union[Path, str]) -> bool:
    try:
        await aiofiles.os.stat(str(path))
    except OSError as e:
        if not pathlib_ignore_error(e):
            raise
        return False
    except ValueError:
        # Non-encodable path
        return False
    return True