Python 截断作为路径的字符串的filname部分。

Python 截断作为路径的字符串的filname部分。,python,Python,我已经在下面贴了一个例子和期望的结果。 我看到了许多消除文件路径部分的方法,但不是相反 示例。 sample = "/tmp/test/helloworld.cpp" sample = truncate_file_name(sample) Print sample /tmp/test 期望的结果 sample = "/tmp/test/helloworld.cpp" sample = truncate_file_name(sample) Print sample /tmp/test

我已经在下面贴了一个例子和期望的结果。 我看到了许多消除文件路径部分的方法,但不是相反

示例。

sample = "/tmp/test/helloworld.cpp"
sample = truncate_file_name(sample)
Print sample
/tmp/test 
期望的结果

sample = "/tmp/test/helloworld.cpp"
sample = truncate_file_name(sample)
Print sample
/tmp/test 

使用
os.path
函数执行以下操作:

>>> import os
>>> os.path.split("/tmp/test/helloworld.cpp")
('/tmp/test', 'helloworld.cpp')

另请参见
os.path.splitext()
os.path.splitdrive()
,等等。另一种方法是,使用
os.path.join()
构造路径-它总是为您的操作系统做正确的事情。

os.path
提供: