本帖最后由 jackz007 于 2019-2-2 12:57 编辑
因为这个脚本的设计有一个基本前提,文件搜索在相对路径下进行,所以,在函数递归中用到了 os . curdir()、os . getcwd()、os . chdir() 等一系列配套函数,当然,完全可以改成基于绝对路径的搜索,就像楼主所愿,把 os . curdir() 改成 start_dir,但是,这需要对其他代码进行相应的修改:
- #!/bin/python
- #coding:gbk
- import os
- def search_file(start_dir , target) :
- try : # 执行下一条语句存在异常风险,加入 try 语句可以处理异常,避免程序意外地退出
- for each_file in os . listdir(start_dir) : # 在 Windows 下,当 start_dir 为无权限路径时,执行该语句会发生异常
- each_file_with_path = start_dir + os . sep + each_file
- if (start_dir[-1] == os . sep) :
- each_file_with_path = start_dir + each_file
- if each_file . upper() == target . upper() : # Windows 文件名比较忽略字母大小写
- print(each_file_with_path) # 使用 os.sep 使程序更标准
- if os . path . isdir(each_file_with_path) :
- search_file(each_file_with_path , target) # 递归调用
- except : # 如果异常发生,就直接从此处继续执行
- pass # 什么都不做
- start_dir = raw_input('请输入待查找的初始目录:') . strip()
- target = raw_input('请输入需要查找的目标文件:') . strip()
- search_file(start_dir, target)
复制代码
加入 try 语句,是为了避免在 Windows 系统下,搜索到没有权限的目录,脚本会出错;在 target 比较中加入 upper() 是为了忽略文件名的大小写铭感。
以下是该脚本在 Python 2.7.13 环境中的运行情况:
G:\[2019]\00.00.Exercise\Python\Searchfile>python Searchfile.py
请输入待查找的初始目录:C:\
请输入需要查找的目标文件:NoTePaD.ExE
C:\Windows\notepad.exe
C:\Windows\System32\notepad.exe
C:\Windows\SysWOW64\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepadwin_31bf3856ad364e35_6.1.7600.1
6385_none_9ebebe8614be1470\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepadwin_31bf3856ad364e35_6.1.7601.1
8917_none_a0f2c3fc11a9f24c\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepadwin_31bf3856ad364e35_6.1.7601.2
3120_none_a16a66f72ad62fe8\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7600.1638
5_none_cb0f7f2289b0c21a\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7601.1891
7_none_cd438498869c9ff6\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7601.2312
0_none_cdbb27939fc8dd92\notepad.exe
C:\Windows\winsxs\wow64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7600.1638
5_none_d5642974be118415\notepad.exe
C:\Windows\winsxs\wow64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7601.1891
7_none_d7982eeabafd61f1\notepad.exe
C:\Windows\winsxs\wow64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7601.2312
0_none_d80fd1e5d4299f8d\notepad.exe
G:\[2019]\00.00.Exercise\Python\Searchfile>