[英]Using os.walk to get my file path in Python
我做了一个简单的脚本,可以找到我的文件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()
使用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兼容的优势。
尝试这个:
$ 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测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.