python - 知道路径的最后一部分和基目录时在python中查找文件的绝对路径?
问题描述
使用 python,我有现有文件路径的最后部分,如下所示:
sub_folder1/file1.txt
sub_folder2/file120.txt
sub_folder78/file99.txt
请注意,这些路径不是我正在工作的当前文件夹的相对路径,例如,这pandas.read_csv('sub_folder1/file1.txt')
将通过一个不存在的文件错误。尽管如此,我知道所有文件都有相同的基本目录base_dir
,但我不知道绝对路径。这意味着文件可以像这样定位:
base_dir/inter_folder1/sub_folder1/file1.txt
或者像这样:
base_dir/inter_folder7/inter_folder4/.../sub_folder1/file1.txt
当给定路径的最后部分和文件的基目录(或等效地,查找中间文件夹)时,是否有返回绝对路径的函数?应该是这样的:
absolut_path = some_func(end_path='bla/bla.txt', base_dir='BLAH')
我认为pathlib
可能有一个解决方案,但在那里找不到任何东西。谢谢
我需要这个来做如下的事情:
for end_path in list_of_paths:
full_path = some_func(end_path=end_path, base_dir='base_dir')
image = cv2.imread(full_path)
解决方案
这应该很容易实现pathlib
:
from pathlib import Path
def find(end_path: str, base_dir: str):
for file in Path(base_dir).rglob("*"):
if str(file).endswith(end_path):
yield file
这是一个generator
, 来匹配pathlib
接口;因此它将产生pathlib.PosixPath
对象。它还会找到所有匹配的文件,例如:
[str(f) for f in find(end_path="a.txt", base_dir="my_dir")]
# creates:
# ['my_dir/a.txt', 'my_dir/sub_dir/a.txt']
如果您只想要第一个值,则可以返回第一项:
def find_first(end_path: str, base_dir: str):
for file in Path(base_dir).rglob("*"):
if str(file).endswith(end_path):
return str(file)
abs_path = find_first(end_path="a.txt", base_dir="my_dir")
可以改善查找的更好功能:
from pathlib import Path
def find(pattern, suffixes, base_dir):
for file in Path(base_dir).rglob(pattern):
if any(str(file).endswith(suffix) for suffix in suffixes):
yield str(file)
base_dir = "base_directory"
suffixes = [
'sub_folder1/file1.txt',
'sub_folder2/file120.txt',
'sub_folder78/file99.txt',
]
for full_path in find(pattern="*.txt", suffixes=suffix, base_dir=base_dir):
image = cv2.imread(full_path)
推荐阅读
- ruby - 如何使用 rest-client 将 cURL multipart/form-data POST 请求转换为 ruby 请求?
- javascript - 我应该在 GraphQL Scalar 中抛出一般错误吗?
- xml - 如何将xml包导入databricks
- javascript - 如何使用变量设置 Ajax Url
- javascript - jsGrid过滤问题从.net控制器调用数据
- react-native - 在 AppState 更改时将 DateTime 值存储在 AsyncStorage 中
- java - SSLHandshakeException:收到致命警报:access_denied
- javascript - 如何将逗号分隔的字符串值转换为数字?
- c++ - 不透明结构与具有私有成员的类
- reactjs - 在 ReactJS 中使用 props 有条件地渲染一个 div