Search code examples
pythonstringos.path

os.path.splitext(file.txt.gz) into (file,.txt.gz)


Currently, I have files that end in /path_to_file/file.txt.gz.

I would like to split the extract the filename (before the .txt.gz).

x = os.path.basename("/path_to_file/file.txt.gz") 

gives me

file.txt.gz

while

os.path.splitext("file.txt.gz")

gives me

('file.txt','.gz')

Is there a function that would separate 'file' from '.txt.gz'?

I suppose I could just use re.sub(), but was wondering if there exists an os.path function.

Thanks.


Solution

  • Surprised that no one has mentioned that the str.split method takes an argument on the maximum number of times to split on that character: e.g., filepath.split('.', 1).