Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Asynchronously check file/folder exists #73

Open
mirismaili opened this issue Mar 20, 2020 · 2 comments
Open

Asynchronously check file/folder exists #73

mirismaili opened this issue Mar 20, 2020 · 2 comments

Comments

@mirismaili
Copy link

mirismaili commented Mar 20, 2020

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

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants