-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_db.py
79 lines (69 loc) · 2.77 KB
/
create_db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import os, time
import sqlite3
import tkinter as tk
from tkinter import filedialog
def index_files(directory):
conn = sqlite3.connect('file_index.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS files
(path TEXT PRIMARY KEY, name TEXT, type TEXT)''')
for root, dirs, files in os.walk(directory):
for dir_name in dirs:
dir_path = os.path.join(root, dir_name)
c.execute('INSERT OR IGNORE INTO files (path, name, type) VALUES (?, ?, ?)', (dir_path, dir_name, 'directory'))
for file in files:
file_path = os.path.join(root, file)
c.execute('INSERT OR IGNORE INTO files (path, name, type) VALUES (?, ?, ?)', (file_path, file, 'file'))
conn.commit()
conn.close()
def choose_directory():
root = tk.Tk()
root.withdraw() # 隐藏主窗口
directory = filedialog.askdirectory(title="Choose Directory to Index")
if directory:
index_files(directory)
def update_database(status_label,stop_event):
start_time = time.time()
status_label.config(text="Start indexing...")
status_label.update_idletasks()
conn = sqlite3.connect('file_index.db')
c = conn.cursor()
# 获取当前数据库中的文件路径
c.execute('SELECT path FROM files')
db_files = set(row[0] for row in c.fetchall())
# 遍历C盘并更新数据库
c_drive_files = set()
for root, dirs, files in os.walk('C:\\'):
if stop_event.is_set():
break
for dir_name in dirs:
if stop_event.is_set():
break
dir_path = os.path.join(root, dir_name)
c_drive_files.add(dir_path)
if dir_path not in db_files:
c.execute('INSERT OR IGNORE INTO files (path, name, type) VALUES (?, ?, ?)', (dir_path, dir_name, 'directory'))
for file in files:
if stop_event.is_set():
break
file_path = os.path.join(root, file)
c_drive_files.add(file_path)
if file_path not in db_files:
c.execute('INSERT OR IGNORE INTO files (path, name, type) VALUES (?, ?, ?)', (file_path, file, 'file'))
# 删除数据库中不存在于C盘中的文件路径
for file_path in db_files:
if stop_event.is_set():
break
if file_path not in c_drive_files:
c.execute('DELETE FROM files WHERE path = ?', (file_path,))
conn.commit()
conn.close()
if stop_event.is_set():
print('stop updating database due to window close')
return
end_time = time.time()
elapsed_time = end_time - start_time
status_label.config(text=f"Indexed within {elapsed_time:.2f} seconds.")
status_label.update_idletasks()
if __name__ == "__main__":
choose_directory()