0

I'm connected to Azure Storage and needs to get the name of a file. I have written a function which gets the list of contents in a particular directory.

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)

And then I'm calling the function

list_directory_contents()

This gives me the something like

folder_name/2020/10/28/file_2020_10_28.csv

Now I want to extract just the file name from the above i.e. "file_2020_10_28.csv"

learningsql
  • 19
  • 1
  • 8
  • Does this answer your question? [partition string in python and get value of last segment after colon](https://stackoverflow.com/questions/6169324/partition-string-in-python-and-get-value-of-last-segment-after-colon) – C.Nivs Oct 28 '20 at 06:48
  • have you tried ``` for path in paths: print(path.name.split("/")[-1] + '\n')``` – HArdRe537 Oct 28 '20 at 06:50

1 Answers1

1

You're looking for os.path.basename. It's a cross platform and robust way to do what you want-

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

in case it wasn't obvious, the part to be changed in list_directory_contents to print only the basename is this-

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

assuming path.name is the string that returns something akin to folder_name/2020/10/28/file_2020_10_28.csv

Chase
  • 5,315
  • 2
  • 15
  • 41
  • Th file path is in terms of a function. When I call the function, I don't think it's returning a string. I tried this = os.path.basename(list_directory_contents()) and I'm not getting the file name. – learningsql Oct 28 '20 at 06:55
  • @learningsql your function isn't returning anything. You should be putting `os.path.basename` in that print part where you're actually printing each path – Chase Oct 28 '20 at 07:05