Should I Use Regex to Get a File Name?
Solution:
import osfile = open('/some/path/to/a/test.csv')fname = os.path.splitext(str(file))[0].split('/')[-1]print(fname)# test
If you get file path and name as string, then:
import osfile = "User/Folder1/test/filename.csv"fname = os.path.splitext(file)[0].split('/')[-1]print(fname)# filename
Explanation on how it works:
Pay attention that command is os.path.splitEXT, not os.path.splitTEXT - very common mistake.
The command takes argument of type string
, so if we use file = open(...)
, then we need to pass os.path.splitext
argument of type string
. Therefore in our first scenario we use:
str(file)
Now, this command splits complete file path + name
string into two parts:
os.path.splitext(str(file))# result:['/some/path/to/a/test','csv']
In our case we only need first part, so we take it by specifying list index:
os.path.splitext(str(file))[0]# result: '/some/path/to/a/test'
Now, since we only need file name and not the whole path, we split it by /
:
os.path.splitext(str(file))[0].split('/')# result:['some','path','to','a','test']
And out of this we only need one last element, or in other words, first from the end:
os.path.splitext(str(file)[0].split('/')[-1]
Hope this helps.
Check for more here: Extract file name from path, no matter what the os/path format