Home > database >  How to get a basename of .tar.gz file in python?
How to get a basename of .tar.gz file in python?

Time:01-18

I would like to get the basename of a tar.gz file in python.

So from "foo/bar/alice.tar.gz" i want alice

What I have so far is:

url = "foo/bar/alice.tar.gz"

Path(Path(url).stem).stem

print(url)

~ alice

is there a smoother way to do so? What if my url is something like "foo/bar/alice.tar.gz.tar.gz.tar.gz" ?

Thanks in advance.

CodePudding user response:

i think that will do the job:

>>> import os
>>> base=os.path.basename("foo/bar/alice.tar.gz")
>>> base
'alice.tar.gz'
>>> name = base.split('.')
'['alice', 'tar', 'gz']'
>>> name = base.split('.')[0]
'alice'

CodePudding user response:

You can use str.partition():

result = Path(url).stem.partition('.')[0]
  •  Tags:  
  • Related