从路径字符串中剥离目录和文件名
我该如何从一个完整的路径字符串中提取出目录和文件名呢?
比如,从:
>>path_string
C:/Data/Python/Project/Test/file.txt
我想得到:
>>dir_and_file_string
Test/file.txt
我认为这应该是字符串操作,而不是文件系统操作。
4 个回答
0
os.path.sep.join(path_string.split(os.path.sep)[-2:])
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
0
我想这算是个小绕弯的解决办法,但效果很好。
path_string = "C:/Data/Python/Project/Test/file.txt"
_,_,_,_,dir_,file1, = path_string.split("/")
dir_and_file_string = dir_+"/"+file1
print dir_and_file_string
1
虽然不是特别优雅,但我还是来试试:
In [7]: path = "C:/Data/Python/Project/Test/file.txt"
In [8]: dir, filename = os.path.split(path)
In [9]: dir_and_file_string = os.path.join(os.path.split(dir)[1], filename)
In [10]: dir_and_file_string
Out[10]: 'Test/file.txt'
这个方法虽然有点啰嗦,但它是可移植的,也很稳健。
另外,你也可以把这个当作字符串操作来处理:
In [16]: '/'.join(path.split('/')[-2:])
Out[16]: 'Test/file.txt'
不过一定要看看为什么要用 os.path.join 而不是字符串拼接。比如说,如果路径里有反斜杠(这是Windows上传统的路径分隔符),那么这个方法就会出问题。用 os.path.sep
代替 '/'
也不能完全解决这个问题。
1
你应该使用 os.path.relpath 这个功能。
import os
full_path = "/full/path/to/file"
base_path = "/full/path"
relative_path = os.path.relpath(full_path, base_path)