【问题标题】:How do I find the path of a file using os.walk?如何使用 os.walk 找到文件的路径?
【发布时间】:2021-01-06 00:17:03
【问题描述】:

如何找到文件的路径?我知道如何找到文件,但路径呢?

from PIL import Image
user_path = "/Users/" + getpass.getuser())

for folder, sub_folder, files in os.walk(user_path):
    for sub_fold in sub_folder:
        for f in files:
            if FileName == f:
                print("file found")

【问题讨论】:

标签: python path


【解决方案1】:

os.walk 产生一个 3 元组 (dirpath, dirnames, filenames),其中 dirpath 是当前目录的路径,这意味着您可以只使用文件名加入:

from PIL import Image
user_path = "/Users/" + getpass.getuser())
for folder, sub_folders, files in os.walk(user_path):
    for f in files:
        if FileName == f:
            print("file found", os.path.join(folder,f))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 2011-12-02
    • 1970-01-01
    • 2015-12-17
    相关资源
    最近更新 更多