在python中从数据帧提取文件夹和文件名
如何从我的数据框中提取folder\filename.txt 我的数据帧:在python中从数据帧提取文件夹和文件名,python,pandas,dataframe,filenames,Python,Pandas,Dataframe,Filenames,如何从我的数据框中提取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
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
稍微修改您的通话:
导入操作系统
df[0]=df[0]。应用(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
如何实现此代码以剪切从特定文件夹开始的文件路径?=
folder
示例,输入:C:/fw/folder/folder1/file.txt
输出:folder/folder1/file.txt
可能使用find()
函数?有很多方法可以做到这一点。这取决于您的用例。通常,我建议尽可能多地使用与操作系统无关的代码,例如合并OS.path子模块。