搜电脑中的某个文件,只显示搜到的第一个
1、找电脑个分区盘符
2、各分区中找文件所在的文件夹
3、输出文件地址
直接上代码
import string
import os
def getDisklist(): # 电脑的各分区盘符
disk_list = []
for c in string.ascii_uppercase:
disk = c + ':'
if os.path.isdir(disk):
disk_list.append(disk)
return disk_list
def searchPath(disk , name): # 搜索某个分区盘 有没有文件 name 只搜一个
file_path = ''
for dir_, dirs, files in os.walk(disk + '\\'): # disk 为根目录 根目录下搜友
if name in dir_ or name in files:
file_path = dir_
break
return file_path
def findPathFile(name): # 查找电脑中的某个文件
path_file = ''
disk_list = getDisklist() # 获取电脑的各分区盘符
for d_i in range(len(disk_list)-1,-1,-1): # C盘内容多,故先搜其他盘
disk = disk_list[d_i]
file_path = searchPath(disk,name)
if file_path:
path_file = file_path + '\\' + name
break
return path_file
name = '002.png'
path_file = findPathFile(name)
if path_file:
print(path_file)
else:
print('没找到文件:', name)
运行结果
D:\iron\002.png