Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Python中的目录内容列表中获取文件名_Python_Filenames_Filepath - Fatal编程技术网

从Python中的目录内容列表中获取文件名

从Python中的目录内容列表中获取文件名,python,filenames,filepath,Python,Filenames,Filepath,我已连接到Azure存储,需要获取文件名。我编写了一个函数,它可以获取特定目录中的内容列表 datepath = np.datetime64('today').astype(str).replace('-', '/') def list_directory_contents(): try: file_system_client = service_client.get_file_system_client(file_system="container_name&q

我已连接到Azure存储,需要获取文件名。我编写了一个函数,它可以获取特定目录中的内容列表

datepath = np.datetime64('today').astype(str).replace('-', '/')
def list_directory_contents():
    try:
       file_system_client = service_client.get_file_system_client(file_system="container_name")

       paths = file_system_client.get_paths(path = "folder_name/" + str(datepath))

       for path in paths:
           print(path.name + '\n')

    except Exception as e:
     print(e)
然后我调用这个函数

list_directory_contents()
这给了我类似的感觉

folder_name/2020/10/28/file_2020_10_28.csv
现在我只想从上面提取文件名,即您要查找的“file\u 2020\u 10\u 28.csv”

。这是一种跨平台、稳健的方式,可以满足您的需求-

>>os.path.basename(“文件夹名称/2020/10/28/file\u 2020\u 10\u 28.csv”)
“文件_2020_10_28.csv”
在不明显的情况下,要在
列表\u目录\u目录
中更改为仅打印基本名称的部分如下-

路径中的路径的
:
打印(os.path.basename(path.name)+'\n')

假设
path.name
是返回类似于
folder\u name/2020/10/28/file\u 2020\u 10\u 28.csv的内容的字符串,这是否回答了您的问题?您是否在路径:print(path.name.split(“/”[-1]+'\n')中尝试过路径“``````第个文件路径是函数形式的。当我调用函数时,我认为它不会返回字符串。我尝试了这个=os.path.basename(list\u directory\u contents()),但没有得到文件名。@learningsql您的函数没有返回任何内容。您应该将
os.path.basename
放在实际打印每个路径的打印部分中