从 python 中的数据框中提取文件夹和文件名

extracting folder and filename from dataframe in python

如何从我的数据框中提取 folder\filename.txt

我的数据框:

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

我需要输出最后一个文件夹和文件名:

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

我的代码:

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

稍微修改一下你的调用:

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

这里,os.sep是系统分隔符,使得调用系统独立。您也可以使用任何其他字符串。

尝试:

# This function takes in input a list and converts it into a dir chain string
def convert(string_list): 

    string = "" 

    # traversing each element of the list and using it to create a new string  
    for x in string_list: 
        string += x + "\"

    # returning string[:-1] to get rid of the redundant \ in the end of the string (not advised when location is of a directory)
    return string[:-1] 


a = r"C:\folder\one\file.txt"

print(convert(a.split("\")[-2:]))

输出:

one\file.txt