Python Forum
Delete files inside Folder and subfolders
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Delete files inside Folder and subfolders
#1
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)
Reply
#2
You can use shutil, see: https://docs.python.org/2/library/shutil.html
Reply
#3
import os

for root, dirs, files in os.walk():
    for file in files:
        # delete the file
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
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)
Reply
#5
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!!
Reply
#6
os.walk() takes as argument the path to a directory.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare folder A and subfolder B and display files that are in folder A but not in su Melcu54 3 545 Jan-05-2024, 05:16 PM
Last Post: Pedroski55
  Rename files in a folder named using windows explorer hitoxman 3 740 Aug-02-2023, 04:08 PM
Last Post: deanhystad
  Rename all files in a folder hitoxman 9 1,488 Jun-30-2023, 12:19 AM
Last Post: Pedroski55
  How to loop through all excel files and sheets in folder jadelola 1 4,488 Dec-01-2022, 06:12 PM
Last Post: deanhystad
  python move folders and subfolders not working mg24 5 2,170 Nov-09-2022, 02:24 PM
Last Post: Larz60+
  python gzip all files from a folder mg24 3 4,005 Oct-28-2022, 03:59 PM
Last Post: mg24
  delete all files and subdirectory from a main folder mg24 7 1,592 Oct-28-2022, 07:55 AM
Last Post: ibreeden
  Merge all json files in folder after filtering deneme2 10 2,344 Sep-18-2022, 10:32 AM
Last Post: deneme2
  delete all files which contains word sql_Table1 mg24 2 865 Sep-15-2022, 10:05 PM
Last Post: mg24
  Delete empty text files [SOLVED] AlphaInc 5 1,566 Jul-09-2022, 02:15 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020