如何找到给定文件的路径?

时间:2009-07-14 11:30:36

标签: python

我有一个文件,例如“something.exe”,我想查找此文件的路径
我怎么能在python中做到这一点?

6 个答案:

答案 0 :(得分:12)

也许os.path.abspath()会这样做:

import os
print os.path.abspath("something.exe")

如果您的something.exe不在当前目录中,则可以传递任何相对路径,abspath()将解析它。

答案 1 :(得分:11)

使用os.path.abspath获取路径名的标准化绝对化版本
使用os.walk获取位置

import os
exe = 'something.exe'
#if the exe just in current dir
print os.path.abspath(exe)
# output
# D:\python\note\something.exe

#if we need find it first
for root, dirs, files in os.walk(r'D:\python'):
    for name in files:
        if name == exe:
            print os.path.abspath(os.path.join(root, name))

# output
# D:\python\note\something.exe

答案 2 :(得分:5)

如果你绝对不知道它在哪里,唯一的办法就是从根c开始找到它:\

import os
for r,d,f in os.walk("c:\\"):
    for files in f:
         if files == "something.exe":
              print os.path.join(r,files)

否则,如果你知道只有很少的地方存储你的exe,比如你的system32,那么就从那里开始找到它。如果你总是将.exe放在PATH变量的其中一个目录中,你也可以使用os.environ [“PATH”]。

for p in  os.environ["PATH"].split(";"):
    for r,d,f in os.walk(p):
        for files in f:
             if files == "something.exe":
                 print os.path.join(r,files)

答案 3 :(得分:2)

呃......这个问题有点不清楚。

你的意思是“拥有”?你有文件的名字吗?你打开它了吗?它是文件对象吗?它是文件描述符吗?什么???

如果这是一个名字,你对“发现”的意思是什么?你想在一堆目录中搜索文件吗?或者你知道它在哪个目录吗?

如果它是文件对象,那么你必须合理地打开它,然后你已经知道了路径,尽管你也可以从fileob.name获取文件名。

答案 4 :(得分:1)

请注意,实现此任务的另一个选项可能是subprocess模块,以帮助我们在终端中执行命令,如下所示:

import subprocess

command = "find"
directory = "/Possible/path/"
flag = "-iname"
file = "something.foo"
args = [command, directory, flag, file]
process = subprocess.run(args, stdout=subprocess.PIPE)
path = process.stdout.decode().strip("\n")
print(path)

通过这个我们模拟将以下命令传递给终端: find /Posible/path -iname "something.foo"。 之后,假设属性stdout是二进制字符串,我们需要解码它,并删除尾随的“\ n”字符。

我在spyder中使用%timeit魔法对其进行了测试,其性能比os.walk()选项慢0.3秒。

我注意到您在Windows中,因此您可以在Unix中搜索与find类似的命令。

最后,如果在不同目录中有多个具有相同名称的文件,则生成的字符串将包含所有这些文件。因此,您需要适当地处理,可能使用正则表达式。

答案 5 :(得分:0)

这确实是旧线程,但对于偶然发现此问题的人可能有用。在python 3中,有一个名为“ glob”的模块,该模块采用“ egrep”样式的搜索字符串并返回系统适当的路径(即Unix \ Linux和Windows)。

https://docs.python.org/3/library/glob.html

示例用法为:

results = glob.glob('./**/FILE_NAME')

然后您将在结果变量中获得匹配项列表。