Python Forum

Full Version: delete all files which contains word sql_Table1
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Team,

how to delete below files from a folder
which contains word sql_Table1


sql_Table1.csv
sql_Table1.gzip
Chksum_sql_Table1_20220806

import os
import os.path

def dbs_remove(folderpath,table)

	file = f'{tbl}.csv'
	fname = os.path.join(folderpath,tbl)
	print(file)

	if os.path.exists(fname):
		os.remove(fname)
	else:
		print('Path not found')



if __name__ == "__main__":
	#tbl = "sql_Table1"
	tbl = input("Enter TableName")
	folderpath = "E:\\test\reports"
Use pathlib:
from pathlib import Path


def remove_files(root, pattern):
    for element in Path(root).rglob(pattern):
        if element.is_file():
            element.unlink()


if __name__ == "__main__":
    tbl = "*sql_Table1*"
    # using the wildcard for rglob()
    folderpath = "E:\\test\reports"
    remove_files(folderpath, tbl)
Hi DeaD_EyE,

Superb ! Thumbs Up your code is working as expected ! thanks for your help.



Thanks
mg