aiofiles icon indicating copy to clipboard operation
aiofiles copied to clipboard

List/delete content of a directory

Open santigandolfo opened this issue 3 years ago • 2 comments

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

santigandolfo avatar Sep 01 '22 03:09 santigandolfo

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.

Tinche avatar Sep 01 '22 11:09 Tinche

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!

santigandolfo avatar Sep 01 '22 14:09 santigandolfo