6

Following this answer, I'm trying to delete the contents of a folder with this code

import os
import glob

files = glob.glob('/YOUR/PATH/*')
for f in files:
    os.remove(f)

But python returns an Attribution Error "'str' object has no attribute 'remove'". What am I'm doing wrong?

4
  • 1
    You would appear to be assigning a string to the variable os. You don't show that code however. Is this all your code? Commented Jan 25, 2016 at 0:24
  • os is not the variable here. And yes, that's all my code. Still no problem solved. Commented Jan 25, 2016 at 0:28
  • os.remove() takes a path as parameter. f is the file name here. Commented Jan 25, 2016 at 0:32
  • 1
    Could you please post the full traceback for the AttributeError exception. Commented Jan 25, 2016 at 0:33

2 Answers 2

11

For deleting an entire directory, use shutil.rmtree('/your/path')

Read more from Python docs

Check out a similar question that has already been answered

Sign up to request clarification or add additional context in comments.

11 Comments

This also deletes the enclosing folder, while I just want to delete the contents inside of it.
@RicardoDahis You can always recreate the empty directory once everything is removed. You dont have to loop through the individual files
Thanks Bob! I'm doing this inside a loop, like for folder in ['/folder1', '/folder2']: shutil.rmtree(path+folder) os.mkdir(path+folder) But os.mkdir returns "'str' object has no attribute 'mkdir'".
@RicardoDahis You have corrupted your os import. You really do appear to have assigned a string to os. How about posting the full traceback?
Am suspecting that something is wrong with the path you are supplying. Try os.mkdir(os.path.join(path, folder))
|
0

As Bob Ezuba said in his answer, shutil.rmtree() is a better way to do it. You can recreate the directory if needed.

Using glob.glob('/your/path/*') will not find hidden files named with a leading .. You could call glob() multiple times, but that's getting ugly. Nor will glob() allow you to differentiate between files and directories, making it difficult to remove subdirectories. shutil.rmtree() will remove all files and subdirectories.

Alternatively you can rename the directory, recreate it anew, then rmtree() the old one. This might be better if you have any processes writing to files in the directory. And it won't leave your directory in a mess if rmtree() fails to remove some of the files, e.g. due to permissions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.