Tinche / aiofiles

File support for asyncio
Apache License 2.0
2.62k stars 151 forks source link

List/delete content of a directory #142

Open santigandolfo opened 1 year ago

santigandolfo commented 1 year ago

How would be the recommended way to list all the files in a directory and then delete them. Using python os you can do it this way:

     def clear_directory(self, dir: str):
        for f in os.listdir(dir):
            os.remove(os.path.join(dir, f))

But I can't seem to find a way to do this with aiofiles.os

Tinche commented 1 year ago

Just take your clear_directory function and run it in a background thread:

from asyncio import get_running_loop

async def coroutine():
    await get_running_loop().run_in_executor(None, clear_directory)

This is what aiofiles would do for you anyway.

santigandolfo commented 1 year ago

Great. I've created this PR #143 to add the listdir function (and also the scandir function) to the main repo. In the meantime I'll be trying your solution. Thanks!