Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Delete all files EXCEPT for

Tags:

python

csv

I have a Python script and I'm trying to delete all files in this directory EXCEPT for the .csv file. Getting syntax error on the "not" in this line:

for CleanUp not in glob.glob("c:\python\AIO*.*"):

If I remove the "not", it will delete the AIO.csv file, but I need to preserve that file and ONLY that file. Not clear why it's not working.

import os
import glob
import time

file_path = "c:\python\AIO.csv"
while not os.path.exists(file_path):
    time.sleep(10)

if os.path.isfile(file_path):
 #Verifies CSV file was created, then deletes unneeded files.
    for CleanUp not in glob.glob("c:\python\AIO*.*"):
        os.remove(CleanUp)
like image 600
user3108489 Avatar asked Jan 06 '23 18:01

user3108489


1 Answers

Try this instead

import os
import glob
import time

file_path = "c:\python\AIO.csv"
while not os.path.exists(file_path):
    time.sleep(10)

if os.path.isfile(file_path):
    # Verifies CSV file was created, then deletes unneeded files.
    for clean_up in glob.glob('C:/python/*.*'):
        print(clean_up)
        if not clean_up.endswith('AIO.csv'):    
            os.remove(clean_up)
      

glob doesn't print any directories, only files, and it also gets the entire path so you can just call os.remove(clean_up). This should work. It works on my machine which is also Windows 7 x64.

I think your problem was that you were looping over the path c:\python\AIO*.* which is a file so it only does one loop and terminates which skips all other files in the directory

like image 172
SirParselot Avatar answered Jan 17 '23 06:01

SirParselot