This article mainly introduces you to the relevant information about using python to operate SQLite database and file operations. The article introduces it in detail through sample code. It has certain reference learning value for everyone's study or work. Friends who need it Let’s learn with the editor below.
Preface
I recently encountered a need at work, which is to delete files with no file names stored in SQLite data. After much deliberation, I decided to use python. So I spent a day and a half studying it and wrote a small example. I won’t say much more below. Friends who are interested can take a look at the detailed introduction.
Upload the code directly
Header file package to be used
#coding=utf-8 #!/usr/bin/python #!/usr/bin/env python import os import shutil import sqlite3
Define record variables
#记录所文件数 sumCount=0; #记录留存文件数 count=0; #记录删除文件数 delCount=0; #定义存储遍历所有文件数组 delList = []
#文件存储路径 delDir = "/Users/liudengtan/Desktop/testFile/" #获取路径下所有文件 delList = os.listdir(delDir) #打开连接数据库 conn = sqlite3.connect('images.db') print "开始处理...";
Put all the files in the file directory Comparison of file and database storage. If the file is in the data, it will be saved. Otherwise, the file will be deleted.
#遍历 for f in delList: #获取到文件路径 filePath = os.path.join(delDir, f) if os.path.isfile(filePath): sumCount=sumCount+1 #将文件全路径中存储路径替换,只留文件名 fileName=filePath.replace(delDir,'') #数据库查看当前文件名是否存在 cursor = conn.execute("SELECT image FROM '表名' where image=(?)",(fileName)) res = cursor.fetchall() #条件判断>0文件存在 if len(res) > 0: count = count + 1; else:#文件不存在将其删除 if os.path.isfile(delDir + fileName): #删除文件操作 os.remove(delDir + fileName) print delDir + fileName + " 删除!" delCount = delCount + 1; #关闭数据库 conn.close() print "处里结束:"; print "所有文件总数 : ",sumCount; print "删除文件数 : ",delCount;
Summary
The above is the detailed content of Detailed explanation of examples of python operating SQLite database and file operations. For more information, please follow other related articles on the PHP Chinese website!