I'm working on a python project that will frequently loop to detect any new folder created in a directory and insert the new folder name into database.
This is shape of the directory and the folders inside it:
C:\USERS\DESKTOP\RESULT
├───20220819_160033
├───20220819_162117
├───20220819_192122
├───20220820_080920
├───20220820_094355
├───20220902_081328
└───20220902_083015
The current algorithm:
I retrieve the previous folder count that have been saved in the database and compared it with current folder counts.
Here's the code:
import pandas as pd
import pyodbc, os
# Connect to SQL Server
conn = pyodbc.connect('Driver={SQL Server};'
'Server=server;'
'Database=folder;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute("SELECT * FROM FileLog ORDER BY FileID DESC")
prevFileCount = cursor.fetchone()
fileCount = prevFileCount[3] # <--- retrieve previous filecounts
name = []
count = 0
dir_path = r'C:\USERS\DESKTOP\RESULT'
# Iterate directory
for path in os.listdir(dir_path): # Calculate current folder counts
# check if current path is a file
if os.path.isdir(os.path.join(dir_path, path)):
name.append(os.path.join(dir_path, path))
count += 1
The idea is, if current counts is more than previous counts, the system will take the total n different and using it to get the last n folder name and save it into database. I found this help but how can I get last n folder name instead of only the last.