-1
string = "C:\\folder\\important\\week1.xlsx"

I need to extract the file name alone, "week1.xlsx" from this string. But for some reason, it doesn't work.

Kabilash
  • 3
  • 3
  • 1
    Those are already single backslashes. They are just escaped. – gre_gor Feb 03 '22 at 06:56
  • I a string like this (not raw) a double backslash represents a single backslash. You should consider using raw strings (`r'...'`) when working with backslashes. – Klaus D. Feb 03 '22 at 06:57
  • `"C:\\folder\\important\\week1.xlsx".split('\\')[-1]` ... ? – Matthias Feb 03 '22 at 06:58
  • Does this answer your question? [Extract file name from path, no matter what the os/path format](https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format) – gre_gor Feb 03 '22 at 07:01

2 Answers2

0

You can use basename:

import os
str(os.path.basename("C:\\folder\\important\\week1.xlsx"))

=> 'week1.xlsx'
Martin Půda
  • 7,353
  • 2
  • 6
  • 13
-1

Try:

filename = string[string.rfind('\\')+1:]

Here's more info on rfind().

Andrej Prsa
  • 551
  • 3
  • 14