0

I have tried to use shutil, but rather than deleting the contents of the folder it just deletes the whole folder.

def delete_song():
    print("Deleting song")
    shutil.rmtree('./song_downloads')
    print("Deleted song")

However it didn't print out "Deleted song". I also tried to use os.remove()

def delete_song():
    print("Deleting song")
    for file in os.listdir('./song_downloads'):
        os.remove(file)
        print("Deleted file")

But this didn't seem to work. Thanks

  • Does this answer your question? [How to delete a file or folder?](https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder) – nngeek Jun 30 '21 at 08:24
  • Check output of os.listdir. It lists only names of files, whilst you need absolute or relative path to file to work with `os.remove`. Probably doing `os.remove(os.path.join('./song_downloads', file)` will solve your issue. – Grysik Jun 30 '21 at 08:34
  • @nngeek I don't think so, these are the solutions I had tried already unfortunately. I have no idea why my loop will not delete all of the files in ./song_downloads, and that seems to be the only solution that will not delete the folder. –  Jun 30 '21 at 08:34
  • @Grysik I do get the error `Failed with: The system cannot find the file specified` when I use the os.remove() method. However the print statement says the exact file name. –  Jun 30 '21 at 08:42

3 Answers3

0

As mentioned in the comment from @grysik on your question, the output of os.listdir() only gives unqualified file names (e.g. no path), therefore the call to os.remove() won't be able to find the file in the current working directory, so you need to pass the path in as well.

The below will do what you require:

def delete_song(directory):
print("Deleting song...")
for f in os.listdir(directory):
    qualified_file=os.path.join(directory, f)
    os.remove(qualified_file)
    print(f"Deleted file [{qualified_file}]")
MrJoosh
  • 33
  • 1
  • 7
0

try using pathlib which allows you to work with the entire Path of the file so you can remove it, and print out the qualified file name.

from pathlib import Path

def delete_song(dir : str) -> None:        
    for file in Path(dir).glob('*'):
        print(f'Removing song --> {file.stem}')
        file.unlink()
    print('Songs deleted.')
Umar.H
  • 22,559
  • 7
  • 39
  • 74
0

If you only want to remove files in a directory, you can try this -

from pathlib import Path

[f.unlink() for f in Path("/path/to/folder").glob("*") if f.is_file()] 
PCM
  • 2,881
  • 2
  • 8
  • 30