简体   繁体   English

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

[英]Using os.walk to get my file path in Python

I've made a simple script which finds my file test.txt, but I am trying to make it return the location of the file. 我做了一个简单的脚本,可以找到我的文件test.txt,但是我试图使其返回文件的位置。 It only returns whether it found the file, but I am struggling to make the function return the file path of the specified file(s), I would like it to return a list of file paths if more than one test.txt was found. 它仅返回是否找到文件,但是我正努力使函数返回指定文件的文件路径,如果找到多个test.txt,我希望它返回文件路径的列表。

Code: 码:

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() 

Use os.path.join to join your file name with the root and return it as a string: 使用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())

If it finds your file, this should print: 如果找到您的文件,则应打印:

C:\path_to_file\test.txt

PS: I see you're using Windows, if you give the path as '/' it will have the same result and provide working paths, with the upside of being compatible with Unix as well. PS:我看到您使用的是Windows,如果将路径指定为'/' ,则将获得相同的结果并提供工作路径,同时还具有与Unix兼容的优势。

Try this: 尝试这个:

$ 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']

It should work in 2.x or 3.x; 它应该在2.x或3.x中工作; tested with 3.3. 用3.3测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM