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"

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 your function isn't returning anything. You should be putting os.path.basename in that print part where you're actually printing each path

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.