xxxxxxxxxx
>>> import os
>>> base=os.path.basename('/root/dir/sub/file.ext')
>>> base
'file.ext'
>>> os.path.splitext(base)
('file', '.ext')
>>> os.path.splitext(base)[0]
'file'
xxxxxxxxxx
# OPTION 1
import os
name = os.path.basename('/root/dir/sub/file.ext').split(".")[0] # returns >file<
# OPTION 2
from pathlib import Path
Path('/root/dir/sub/file.ext').stem # returns >file<
# Note that if your file has multiple extensions .stem will only remove the last extension.
# For example, Path('file.tar.gz').stem will return 'file.tar'.
xxxxxxxxxx
#Using pathlib in Python 3.4+
from pathlib import Path
Path('/root/dir/sub/file.ext').stem
xxxxxxxxxx
import os
import sys
def txt_finder(path):
for dirname in os.listdir(path):
name, ext = os.path.splitext(dirname)
file = f'{path}\{name}'
if ext == '.txt':
# do some work with this file using file variable
# process_txt(file)
pass
elif ext == '':
# if it's a folder we dive in it.
txt_finder(file)
if __name__ == '__main__':
txt_finder(path=sys.path[0])