Using python to operate SQLite databases and files,
Preface
Recently, I encountered a need to delete files with no stored file names in SQLite data. I want to decide whether to use python. So I spent a day and a half learning about it. I wrote a small example by hand. I will not talk much about it below. If you are interested, let's take a look at the detailed introduction.
Directly Add code
Header package to be used
#coding=utf-8#!/usr/bin/python#!/usr/bin/env pythonimport osimport shutilimport sqlite3
Define record Variables
# Record the number of files sumCount = 0; # record the number of stored files count = 0; # record the number of deleted files delCount = 0; # define storage to traverse all file arrays delList = []
# File storage path delDir = "/Users/liudengtan/Desktop/testFile/" # obtain all files in the path delList = OS. listdir (delDir) # Open the Connection database conn = sqlite3.connect ('images. db') print "Start processing... ";
Compare all files in the file directory with those stored in the database. If the files are stored in the data, they will be retained; otherwise, the files will be deleted.
# Traverse for f in delList: # obtain the file path filePath = OS. path. join (delDir, f) if OS. path. isfile (filePath): sumCount = sumCount + 1 # Replace the storage path in the full path of the file, leaving only the file name fileName = filePath. replace (delDir, '') # Check whether the current file name contains cursor = conn.exe cute (" SELECT image FROM 'table name' where image = (?) ", (FileName) res = cursor. fetchall () # condition judgment> 0 file if len (res)> 0: count = count + 1; else: # Delete if OS if the file does not exist. path. isfile (delDir + fileName): # delete file OS. remove (delDir + fileName) print delDir + fileName + "Delete! "DelCount = delCount + 1; # disable database conn. close () print "ending in:"; print "Total number of all files:", sumCount; print "Number of deleted files:", delCount;
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.