Delete a file with all its contents in Python

2

I would like to delete a directory that contains several files inside. It has the following structure:

carpeta
    fichero1.txt
    fichero2.txt

I tried to delete it directly with os.removedirs('carpeta') but it gives me the error Directory not empty: 'carpeta' . Also try to delete the files first and then the directory in the following way:

import os
os.remove('carpeta/fichero1.txt')
os.remove('carpeta/fichero2.txt')
os.removedirs('carpeta')

This, although it deletes the files to me, when it is going to delete the folder it continues giving me the same error; and even if it works it is not recommended because I do not know how many files I will have in that folder.

    
asked by Reinier Hernández Ávila 20.09.2017 в 22:30
source

1 answer

4

To delete the directory and all its contents, use shutil.rmtree of the library standard. There are other options like using operating system commands using os.system or subprocess , but this is the simplest thing to do.

import shutil
shutil.rmtree("carpeta")

In addition, it is platform-independent.

    
answered by 20.09.2017 / 22:36
source