Python Forum
Delete files inside Folder and subfolders - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Delete files inside Folder and subfolders (/thread-3807.html)



Delete files inside Folder and subfolders - zinho - Jun-26-2017

Hi.

I want delete only files inside MainFolder and subfolder, but not delete folders.
[Image: kJoqnk]

I try sominth like below
import glob

files = glob.glob('C:/Users/zinho/Downloads/MainFolder/*')
for f in files:
   os.remove(f)



RE: Delete files inside Folder and subfolders - Larz60+ - Jun-26-2017

You can use shutil, see: https://docs.python.org/2/library/shutil.html


RE: Delete files inside Folder and subfolders - wavic - Jun-27-2017

import os

for root, dirs, files in os.walk():
    for file in files:
        # delete the file



RE: Delete files inside Folder and subfolders - zinho - Jun-27-2017

Show error "TypeError: walk() missing 1 required positional arqument: 'top' "
import os
import glob
files = glob.glob('C:/Users/zinho/Downloads/MainFolder/*')
for root, dirs, files in os.walk():
	for file in files:
		os.remove(file)



RE: Delete files inside Folder and subfolders - zinho - Jun-27-2017

I find a solution

import os

os.chdir("C:\\Users\\zinho\\Downloads\\MainFolder")
for root, dirs, files in os.walk(".", topdown = False):
   for file in files:
      print(os.path.join(root, file))
      os.remove(os.path.join(root, file))
It's solved, thank you!!


RE: Delete files inside Folder and subfolders - wavic - Jun-27-2017

os.walk() takes as argument the path to a directory.