在Python中使用os.walk获取文件路径

1 投票
2 回答
3859 浏览
提问于 2025-04-17 23:01

我写了一个简单的脚本,用来查找我的文件 test.txt,但我想让它返回文件的位置。现在它只告诉我是否找到了这个文件,但我在让这个函数返回指定文件的路径上遇到了困难。如果找到了多个 test.txt,我希望它能返回一个文件路径的列表。

代码:

import os

wallet = 'test.txt'
filepath = 'C:\\'

def search():
    for root,dirs,files in os.walk(filepath):
        if wallet in files:
            return 'File found'
        else:
            return 'Nope.. not here'
print search() 

2 个回答

0

试试这个:

$ cat walk
#!/usr/local/cpython-3.3/bin/python

import os

wallet = 'stdio.h'
filepath = '/usr'

def search():
    for root, dirs, files in os.walk(filepath):
        if wallet in files:
            yield os.path.join(root, wallet)

print(list(search()))

zareason-dstromberg:~/src/outside-questions/walk x86_64-pc-linux-gnu 13799 - above cmd done 2014 Wed Mar 19 12:16 PM

$ ./walk
['/usr/include/stdio.h', '/usr/include/x86_64-linux-gnu/bits/stdio.h', '/usr/include/c++/4.7/tr1/stdio.h']

这个在2.x或3.x版本中都应该能用;我在3.3版本上测试过。

1

使用 os.path.join 可以把你的文件名和根目录连接起来,并把结果返回为一个字符串:

import os

wallet = 'test.txt'
filepath = r'C:\\'

def search():
    for root,dirs,files in os.walk(filepath):
        if wallet in files:
            return os.path.join(root, wallet)
        else:
            return 'Nope.. not here'
print(search())

如果找到了你的文件,应该会打印出:

C:\path_to_file\test.txt

另外,我注意到你在用Windows系统,如果你把路径写成 '/',结果也是一样的,而且可以正常使用,这样做的好处是也能和Unix系统兼容。

撰写回答