0

I have a list variable which has elemnts like below: ['Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131121.csv', 'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131150.csv', 'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131160.csv', 'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131169.csv', 'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131189.csv']

This is file name with file path in it. Want to build a list with only file name, how can i do that? Output should be:

['bounce-20211109-131121.csv', 'bounce-20211109-131150.csv', 'bounce-20211109-131160.csv', 'bounce-20211109-131169.csv', 'bounce-20211109-131189.csv'] ie strip out string 'Cordial/contactactivity/export/bounce/0-ContactActivity-'

python_user
  • 5,375
  • 2
  • 13
  • 32
CRP
  • 9
  • 2
  • 2
    Does this answer your question? [Extract file name from path, no matter what the os/path format](https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format) – heijp06 Nov 11 '21 at 16:23

1 Answers1

3

You can use os.path.basename (docs here) and get the last segment. Then you just need to trim the part you don't want.

import os
data = [
    'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131121.csv', 
    'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131150.csv',
    'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131160.csv',
    'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131169.csv',
    'Cordial/contactactivity/export/bounce/0-ContactActivity-bounce-20211109-131189.csv'
]
data = [os.path.basename(i).replace('0-ContactActivity-', '') for i in data]

resulting in:

>>> data
['bounce-20211109-131121.csv', 'bounce-20211109-131150.csv', 'bounce-20211109-131160.csv', 'bounce-20211109-131169.csv', 'bounce-20211109-131189.csv']
Rafael Barros
  • 2,738
  • 1
  • 21
  • 28
  • 1
    Why not just use [`basename`](https://docs.python.org/3/library/os.path.html#os.path.basename)? *"Return the base name of pathname path. __This is the second element of the pair returned by passing path to the function split()__"* – Tomerikoo Nov 11 '21 at 16:29
  • 1
    It works, Thank you! – CRP Nov 11 '21 at 16:31
  • Can also use [`removeprefix`](https://docs.python.org/3/library/stdtypes.html#str.removeprefix) (Python >= 3.9) instead of `replace` – Tomerikoo Nov 11 '21 at 16:33
  • @Tomerikoo good point. – Rafael Barros Nov 12 '21 at 17:10