0

I have a class with a method called delete that should completely erase the "hold_files" variable. I'd like to mimic deleting an actual folder in the terminal, then itself. For example, "rm -f". Is that possible?

Also, how would I prove that hold_files is completely gone?

class directory:
  hold_files = [
    'test1.txt', 'test2.py',
    {'/desktop': ['computer.txt','tfile.doc',
      {'/steph':{
        '/pictures': [
        'hello.gif',
        'smile.gif',
        'run.gif'
        ]},
    '/work':[
    'file1.txt',
    'file2.txt'
    ]
      }]
    }
  ]

#recursively delete folder

  def delete(itself):
    #if dictionary, call self, else delete
    if len(itself)>0:
        for f in itself:
            print(type(f))
            if type(f) is dict:
                delete(f)
            else:
                itself.remove(f)
                

This is calling the method:

directory.delete(hold_files)

Thank you.

Colorful Codes
  • 577
  • 4
  • 16
  • see https://stackoverflow.com/questions/10112601/how-to-make-scripts-auto-delete-at-the-end-of-execution – frozen Aug 08 '20 at 22:46
  • @frozen This is different as I'd need a simulation of an actual deletion and then the entire variable. – Colorful Codes Aug 08 '20 at 22:51
  • you have some style and possible correctness issues. Classes should usually be named with an uppercase first character. the delete method is written as an instance method (no static method annotation) so should have a self arg in addition to the itself arg. finally the call of the method should be to an instance of the method, right now you are just calling it direct as a class method. makes it a bit confusing to read. – LhasaDad Aug 08 '20 at 22:56
  • I don't understand. You can remove an attribute by doing `del my_obj.myattribute` – juanpa.arrivillaga Aug 08 '20 at 23:24
  • Your program yields the error `NameError: name 'hold_files' is not defined`. `hold_files` is defined within the class. Also the function `delete` is not `defined. – Yuri Ginsburg Aug 08 '20 at 23:26

1 Answers1

1

You should be able to use del to delete a variable, and then try using the variable to check if it's really gone. If you get an error, it's gone. `

>>> number = 1
>>> del number
>>> data = number
Traceback (most recent call last):
    File "<pyshell#2>", line 1, in <module>
        data = number
NameError: name 'number' is not defined
>>> 

`

  • Yes, I understand thank you, but is there a way to simulate the recursive deletion of the files within the folders until everything is completely gone. If I put this code in a visualizer, it just deletes the variable. I'd like to step through the deletion of each file/folder in the json. – Colorful Codes Aug 09 '20 at 14:18
  • You could probably just change your loop to use the `del` statement instead of your undefined `delete()` function. – BerkZerker707 Aug 09 '20 at 21:36