Python Operation example of SQLite database and file operation

Source: Internet
Author: User
Tags sqlite database
This article mainly introduces the use of Python operation SQLite database and file operation of the relevant information, the text through the sample code introduced in very detailed, to everyone's study or work has a certain reference learning value, the need for friends below with the small series to learn together.

Objective

Recently encountered in the work of a demand, is to be the SQLite data is not stored in the file name of files deleted, want to go or decide to use Python. So it took a day and a half of the time to learn the next, handy to write a small example, the following words do not say, interested friends together to see the detailed introduction it.

Directly on the code

Header file package to be used


#coding =utf-8#!/usr/bin/python#!/usr/bin/env pythonimport osimport shutilimport sqlite3

Defining record variables


#记录所文件数sumCount =0; #记录留存文件数count =0; #记录删除文件数delCount =0; #定义存储遍历所有文件数组delList = []


#文件存储路径delDir = "/users/liudengtan/desktop/testfile/" #获取路径下所有文件delList = Os.listdir (deldir) #打开连接数据库conn = Sqlite3.connect (' images.db ') print "Start processing ...";

Compare all files in the file directory with the database, if the file is in the data, persist, otherwise delete the file


#遍历for f in dellist: #获取到文件路径 FilePath = Os.path.join (Deldir, F) if Os.path.isfile (filePath):  sumcount=sumcount+1
   #将文件全路径中存储路径替换, leave only the filename  filename=filepath.replace (deldir, ")  #数据库查看当前文件名是否存在  cursor = Conn.execute (" SELECT image from ' table name ' where image= (?) ', (fileName))  res = Cursor.fetchall ()  #条件判断 >0 file exists  if Len (res) > 0:   count = count + 1;  else: #文件不存在将其删除   if Os.path.isfile (deldir + filename):    #删除文件操作    os.remove (deldir + filename)    Print Deldir + fileName + "Delete!"   Delcount = Delcount + 1; #关闭数据库conn. Close () print "at end:";p rint "Total Files:", sumcount;print "number of files deleted:", Delcount;

Summarize

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.