gpt4 book ai didi

python - Python如何向上查找文件?

转载 作者:行者123 更新时间:2023-11-28 22:07:58 25 4
gpt4 key购买 nike

在 Python 中“向上”查找文件的最佳方法是什么? (理想情况下它也适用于 Windows)。例如,

>>> os.makedirs('/tmp/foo/bar/baz/qux')
>>> open('/tmp/foo/findme.txt', 'w').close()
>>> os.chdir('/tmp/foo/bar/baz/qux')
>>> findup('findme.txt')
'/tmp/foo/findme.txt'

据我所知,Python 标准库中没有任何内容(尽管我希望被证明是错误的)。此外,谷歌搜索并没有发现太多确定的信息;我想知道是否有“每个人”都在使用的东西。

最佳答案

import os

def findup(filename):
drive, thisdir = os.path.splitdrive(os.getcwd())
while True:
fullpath = os.path.join(drive, thisdir, filename)
if os.path.isfile(fullpath):
return fullpath
if thisdir == os.path.sep: #root dir
raise LookupError('file not found: %r' % filename)
thisdir = os.path.dirname(thisdir)

os.makedirs('/tmp/foo/bar/baz/qux')
open('/tmp/foo/findme.txt', 'w').close()
os.chdir('/tmp/foo/bar/baz/qux')
print findup('findme.txt')

打印:

/tmp/foo/findme.txt

也适用于 Windows。可能适用于任何平台。

关于python - Python如何向上查找文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/899273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com