Reputation: 111
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'
Upvotes: 0
Views: 1042
Reputation: 380
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
Upvotes: 1
Reputation: 751
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'
Upvotes: 1
Reputation: 2078
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];
Upvotes: 0