Search code examples
pythonpandasdataframefilenames

extracting folder and filename from dataframe in python


How to extract folder\filename.txt from my dataframe

my dataframe:

C:\folder\one\file.txt
C:\folder\subfolder\two\file2.txt

I need on output last folder and filename:

df:
one\file.txt
two\file2.txt

my code:

df[0] = df[0].apply(lambda x: x.split('\\')[-1]) # i am receiving only file.txt - only filename , not last folder and filename

Solution

  • Slightly modify your call:

    import os
    df[0] = df[0].apply(lambda x: os.sep.join(x.split('\\')[-2:])))
    

    Here, os.sep is the system separator, which makes the call system independent. You could use any other string, too.