-2

WARNING WHEN USING THIS FILE IT CAN DELETE FILES ON THE SAME FOLDER

hi this is a python 3 script for deleting files i wonder how to prevent it from deleting itself

the code:

import os
import sys
import glob
fileList = glob.glob('*.*')
print(fileList)
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)
Machavity
  • 30,841
  • 27
  • 92
  • 100

2 Answers2

0

You can use os.path.basename(__file__) to get the name of the current script. So it can compare filePath with this, and skip it.

import os
import sys
import glob

current_script = os.path.basename(__file__)
fileList = glob.glob('*.*')
print(fileList)
for filePath in fileList:
    if filePath != current_script:
        try:
            os.remove(filePath)
        except:
            print("Error while deleting file : ", filePath)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Good answer, except that I think `current_script = sys.argv[0]` would be slightly more idiomatic. – Julia Mar 06 '21 at 23:06
  • 1
    I used the answer with the highest votes here: https://stackoverflow.com/questions/4152963/get-name-of-current-script-in-python – Barmar Mar 06 '21 at 23:08
  • @Barmar thank you , can you help how to make this code delete subfolder fills and folders or i must ask another question , sorry I'm new – Aymen Hmani Mar 06 '21 at 23:47
  • See https://stackoverflow.com/questions/13118029/deleting-folders-in-python-recursively – Barmar Mar 07 '21 at 00:59
0

You were getting all file names and then deleting them. If you just add this simple step... 1. Get all file names, 2. exclude the file name you don't want to delete, then 3. Delete the remaining file names.

import os
import sys
import glob

current_script = os.path.basename(__file__)
fileList = glob.glob('*.*')
fileList.remove(current_script)
print(fileList)
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)
Saad Rehman Shah
  • 926
  • 2
  • 10
  • 28