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'

2
  • 1
    filename.split('\')[-1] is the problem you need to escape the backslash ("\\") if you wanna treat it literally. Commented Mar 29, 2019 at 10:03
  • Possible duplicate; stackoverflow.com/questions/8384737/… Commented Mar 29, 2019 at 10:10

3 Answers 3

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' 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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]; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.