-1

I do know about os.remove() I am working on - When an excel file is created into a folder then the script runs and it will add the excel file data into the particular columns of the table of database. What I want is the file should be deleted from that folder just after running the script so that when a new excel file is created into the folder the script will again runs and add the new data into the database and so on. I am a newbie to the python and as I know os.remove needs file name to be entered.

Is there any other function of doing this? Here is my script

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import ibm_db
import ibm_db_dbi
import os
import xlrd

class ExampleHandler(FileSystemEventHandler):
    def on_created(self, event):
        connection = ibm_db.connect("DATABASE=xyz; HOSTNAME=xyz; PORT=xyz; PROTOCOL=xyz; UID=xyz; PWD=xyz;","","")
        conn = ibm_db_dbi.Connection(connection)
        cur = conn.cursor()

        query = "INSERT INTO EXCELUPLOAD (qty, amt, num, code, name) VALUES (?,?,?,?,?)"

        for r in range(1, sheet.nrows):
                qty  = sheet.cell(r,0).value
                amt  = sheet.cell(r,1).value
                num  = sheet.cell(r,2).value
                code = sheet.cell(r,3).value
                name = sheet.cell(r,4).value
    
                values = (qty, amt, num, code, name)
                cur.execute(query, values)
    
        cur.close()
        conn.commit()
        conn.close()
        

observer = Observer()
event_handler = ExampleHandler()

observer.schedule(event_handler, path=r'D:\New folder')
observer.start()

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
    observer.join()
GD201
  • 13
  • 3

1 Answers1

1

You could use os.listdir() to list all files of a given folder.

Then you could either delete all files or delete files based on their file name or file type/suffix.

E. g.:

import os
from pathlib import Path

files = os.listdir("your/path")
for file in files:
    os.remove(file) # delete all files

    if Path(file).name == "Test" or Path(file).suffix == ".txt":
        os.remove(file) # delete file based on their name or suffix
Admin
  • 91
  • 5