我使用以下代码来获取容器中子目录中的文件:
from azure.storage.filedatalake import DataLakeServiceClient
remote_paths = service_client.get_file_system_client("mycontainer").get_paths(path="a/b/c")
问题是
get_paths()
返回c
所有子目录中的所有文件和文件夹,但我只对目录c
中的文件感兴趣。
我知道
.is_directory
,但这仍然会返回子目录中的文件。
我可以从结果集中删除路径(
a/b/c
),然后检查/
是否存在,这表明该文件位于子文件夹中,但我想知道是否有更好的方法?
你说得对,Azure DataLakeServiceClient 中的“get_paths()”方法确实返回了指定路径及其子目录中的所有文件和文件夹。 不幸的是,没有内置的方法可以将其限制为仅限顶级目录。
但是,您仍然可以通过检查路径名称是否包含初始目录之外的任何其他斜杠来过滤结果,以仅包含顶级目录中的文件。以下是如何执行此操作的示例:
from azure.storage.filedatalake import DataLakeServiceClient
def get_top_level_files(service_client, container_name, directory_path):
file_system_client = service_client.get_file_system_client(container_name)
paths = file_system_client.get_paths(path=directory_path)
top_level_files = []
for path in paths:
# Check if the path is a file and is in the top-level directory
if not path.is_directory and '/' not in path.name[len(directory_path):]:
top_level_files.append(path)
return top_level_files
用途: service_client = DataLakeServiceClient(...) top_level_files = get_top_level_files(service_client, "mycontainer", "a/b/c")
在这段代码中,path.name[len(directory_path):]获取路径名中指定目录后面的部分,path.name[len(directory_path):]中的'/'则检查这部分是否存在。
不幸的是,我不认为有更简单的方法来实现这一点,但这个方法是可靠的。