寻找并列出电脑上除去系统文件夹和管理员文件夹的所有.txt、.exe、.doc、.docx文件,并发送至数据库。
import os
import wmi
import pyodbc
import glob
'''使用 glob的glob.iglob()函数匹配所有文件位置的文件,缺点慢、占用CPU资源较高。'''
# def file_information():
# drives = [chr(x) + ':' for x in range(65, 90) if os.path.exists(chr(x) + ':')]
# text1 = ['/**/*.txt', '/**/*.exe', '/**/*.doc', '/**/*.docx']
# exclude_dirs = ['C:/Users\\Administrator', 'C:/Windows', 'C:/Program Files', 'C:/Program Files (x86)',
# 'C:/ProgramData']
# file_name = []
# file_path = []
# file_size = []
# for drive in drives:
# for a in text1:
# for filename in glob.iglob(drive + a, recursive=True):
# if not any(exclude_dir in filename for exclude_dir in exclude_dirs):
# file_name.append(os.path.basename(filename))
# file_path.append(filename)
# size_a = (os.path.getsize(filename))
# file_size.append(str((int((size_a / 1024) + 1))) + 'KB')
#
# return file_name, file_path, file_size
'''使用os的os.walk()函数递归遍历磁盘,很快,不怎么占用CPU资源,但是运行期间硬盘资源会被占满,机械硬盘的电脑慎用'''
# 返回值:str文件名、str文件路径、str文件大小
def file_information():
file_name = []
file_path = []
file_size = []
# 获取计算机所有的盘符
drives = [chr(x) + ':' for x in range(65, 90) if os.path.exists(chr(x) + ':')]
for drive in drives:
for root, dirs, files in os.walk((drive + "/")):
# 排除系统文件夹和管理员文件夹
dirs[:] = [d for d in dirs if
d not in ['Windows', 'Program Files', 'Administrator', 'Program Files (x86)', 'ProgramData']]
for file in files:
# 筛选带txt、exe、doc、docx类型的文件
if file.endswith(".txt") or file.endswith(".exe") or file.endswith(".doc") or file.endswith(".docx"):
file_name.append(file) # 文件名
file_path.append(os.path.join(root, file)) # 文件路径
file_size.append(
str((int(((os.path.getsize(os.path.join(root, file))) / 1024) + 1))) + 'KB') # 文件大小
return file_name, file_path, file_size
# 返回值:str电脑名、str电脑使用人
def computer_information():
# 读取电脑配置信息
w = wmi.WMI()
pc_name = '' # 电脑名称
user_name = '' # 电脑使用人
for BIOSs in w.Win32_ComputerSystem():
pc_name += BIOSs.Caption # 电脑名称
user_name += BIOSs.UserName # 电脑使用人
user_name = user_name.replace('\\', '-') # 替换符号
return pc_name, user_name
def sql_statement(lile_list, pc_information):
# 连接到SQL Server数据库
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=数据库地址;DATABASE=数据库名称;UID=账号;PWD=密码')
# 创建游标
cursor = conn.cursor()
# SQL命令,删除电脑名为指定名称的所有条目。
data2 = "if exists(select * from 表名 where 字段—电脑名='" + pc_information[
0] + "') begin delete from 表名 where 字段—电脑名='" + pc_information[0] + "' end"
insert_query = "INSERT INTO 表名 (字段—文件名, 字段—文件路径, 字段—电脑名, 字段—电脑使用人, 字段—文件大小) VALUES (?, ?, ?, ?, ?)"
data1 = []
for i in range(len(lile_list[0])):
data1.append((lile_list[0][i], lile_list[1][i], pc_information[0], pc_information[1], lile_list[2][i]))
# 执行判断删除语句
cursor.execute(data2)
# 执行插入操作
cursor.executemany(insert_query, data1)
# 提交事务
conn.commit()
# 关闭连接
conn.close()
file_i = file_information()
computer_i = computer_information()
sql_statement(file_i, computer_i)