gag*_*nso 7 python python-2.7 python-3.x
是否有内置模块来搜索当前目录中的文件以及所有超级目录?
没有模块,我将列出当前目录中的所有文件,搜索有问题的文件,并在文件不存在时递归向上移动.有更简单的方法吗?
另一种选择,使用pathlib:
from pathlib import Path
def search_upwards_for_file(filename):
"""Search in the current directory and all directories above it
for a file of a particular name.
Arguments:
---------
filename :: string, the filename to look for.
Returns
-------
pathlib.Path, the location of the first file found or
None, if none was found
"""
d = Path.cwd()
root = Path(d.root)
while d != root:
attempt = d / filename
if attempt.exists():
return attempt
d = d.parent
return None
Run Code Online (Sandbox Code Playgroud)
这是另一种,使用 pathlib:
from pathlib import Path
def find_upwards(cwd: Path, filename: str) -> Path | None:
if cwd == Path(cwd.root) or cwd == cwd.parent:
return None
fullpath = cwd / filename
return fullpath if fullpath.exists() else find_upwards(cwd.parent, filename)
# usage example:
find_upwards(Path.cwd(), "helloworld.txt")
Run Code Online (Sandbox Code Playgroud)
(此处使用一些 Python 3.10 键入语法,如果您使用的是早期版本,则可以安全地跳过该语法)
那么这不是很好实现,但会起作用
用于listdir获取当前目录中的文件/文件夹列表,然后在列表中搜索您的文件.
如果它存在循环中断,但如果它不存在则使用os.path.dirname和转到父目录listdir.
如果cur_dir == '/'父目录for "/"返回,"/"如果cur_dir == parent_dir它打破了循环
import os
import os.path
file_name = "test.txt" #file to be searched
cur_dir = os.getcwd() # Dir from where search starts can be replaced with any path
while True:
file_list = os.listdir(cur_dir)
parent_dir = os.path.dirname(cur_dir)
if file_name in file_list:
print "File Exists in: ", cur_dir
break
else:
if cur_dir == parent_dir: #if dir is root dir
print "File not found"
break
else:
cur_dir = parent_dir
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26354 次 |
| 最近记录: |