0

I am trying to get the the file name along with extension from a path I tried few codes but I am unable to get the file name.

filename = '/home/lancaster/Downloads/a.ppt'
extention = filename.split('/')[-1]

This works fine for the file path given there but when I try for file path which has '\' backward slash it takes it as an escape sequence and throws this error EOL while scanning string literal

filename = '\home\lancaster\Downloads\a.ppt'
extention = filename.split('\')[-1]

This throws error EOL while scanning string literal

filename = '\home\lancaster\Downloads\a.ppt'
extention = filename.split('\')[-1]

Expected result is

a.ppt

but throws

'EOL while scanning string literal'

Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    `filename.split('\')[-1]` is the problem you need to escape the backslash (`"\\"`) if you wanna treat it literally. – Mazdak Mar 29 '19 at 10:03
  • Possible duplicate; https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format – PySaad Mar 29 '19 at 10:10

3 Answers3

1

The path you are using uses '\' which will be treated as escape character in python. You must treat your path as raw string first and then split it using '\':

>>> r'\home\lancaster\Downloads\a.ppt'.split('\\')[-1]
'a.ppt'
Sabareesh
  • 711
  • 1
  • 7
  • 14
1

Compilers do not just understand '\'. It is always '\' followed by another character. eg:'\n' represents new line. Similarly, you need to use '\' instead of '\' to represent a '\'.

In other words, you can change your code from filename.split('\')[-1] into filename.split('\\')[-1]

This should give you your required output

Sridhar Murali
  • 380
  • 1
  • 11
0

I would suggest using module os and for example:

import os
filename = '\home\lancaster\Downloads\a.ppt'
basename = os.path.basename(filename)
extension = basename.split('.')[1];
msi_gerva
  • 2,021
  • 3
  • 22
  • 28