Python:当只有文件名(不是路径)可用时,如何在系统范围内搜索文件 [英] Python: How to do a system wide search for a file when just the filename (not path) is available

查看:48
本文介绍了Python:当只有文件名(不是路径)可用时,如何在系统范围内搜索文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是 Python 的新手(使用 2.6),当只有文件名可用时,我试图在系统范围内搜索文件并返回 Windows 上的绝对路径.我搜索并找到了一些像 scriptutil.py 这样的模块,并查看了 os 模块,但没有找到任何适合我的需求(或者我可能没有正确理解所有内容以将其应用于我需要的内容,因此没有包含任何代码).我将不胜感激.

I'm still new to Python (using 2.6) and I am trying to do a system wide search for a file when just the filename is available and return the absolute path on windows. I've searched and found some modules like scriptutil.py and looked through the os module but haven't found anything that suits my needs (or I may not have understood everything correctly to apply it to what I need and thus have not included any code). I would appreciate any help.

谢谢.

推荐答案

os.walk() 函数是一种方法.

The os.walk() function is one way of doing it.

import os
from os.path import join

lookfor = "python.exe"
for root, dirs, files in os.walk('C:\\'):
    print "searching", root
    if lookfor in files:
        print "found: %s" % join(root, lookfor)
        break

这篇关于Python:当只有文件名(不是路径)可用时,如何在系统范围内搜索文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆