【问题标题】:Get file name from list of directory contents in Python从 Python 中的目录内容列表中获取文件名
【发布时间】:2020-10-28 06:45:12
【问题描述】:

我已连接到 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_2020_10_28.csv”

【问题讨论】:

标签: python filenames filepath


【解决方案1】:

您正在寻找os.path.basename。这是一种跨平台且强大的方式来做你想做的事-

>>> os.path.basename("folder_name/2020/10/28/file_2020_10_28.csv")
'file_2020_10_28.csv'

如果不是很明显,list_directory_contents 中要更改以仅打印基本名称的部分是 this-

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

假设path.name 是返回类似于folder_name/2020/10/28/file_2020_10_28.csv 的字符串

【讨论】:

  • 文件路径是以函数的形式存在的。当我调用该函数时,我认为它不会返回一个字符串。我试过这个 = os.path.basename(list_directory_contents()) 但我没有得到文件名。
  • @learningsql 你的函数没有返回任何东西。您应该将os.path.basename 放在实际打印每个路径的打印部分中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-29
  • 2011-03-05
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
相关资源
最近更新 更多