[英]How to carry in a list the name each file from a directory with python?
[英]Get file name from list of directory contents in Python
我已连接到 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”
您正在寻找os.path.basename
。 这是一个跨平台和强大的方式来做你想做的事-
>>> os.path.basename("folder_name/2020/10/28/file_2020_10_28.csv")
'file_2020_10_28.csv'
如果不明显,在list_directory_contents
要更改以仅打印基本名称的部分是这个 -
for path in paths:
print(os.path.basename(path.name) + '\n')
假设path.name
是返回类似于folder_name/2020/10/28/file_2020_10_28.csv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.