我做了一个简单的脚本找到我的文件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()
答案 0 :(得分: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
PS:我看到你正在使用Windows,如果你给路径'/'
它将具有相同的结果并提供工作路径,并具有与Unix兼容的优点。
答案 1 :(得分: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测试。