的Python:绝对路径相对让到另一条路径
问题描述:
假设我有两个文件路径为Python字符串,作为一个例子,让我们说他们是这两个:的Python:绝对路径相对让到另一条路径
C:/Users/testUser/Program/main.py
C:/Users/testUser/Program/data/somefile.txt
有没有一种方法,使用的操作系统模块,以生成一个基于第一个的相对URL?例如,进给上述两个,以产生:
data/somefile.txt
我明白,这是可能的字符串操作,通过在端部分割断的文件和切割所述第一串从第二的,但有一个更强大的方式,大概使用python os
模块?
答
由于MPlanchard在下面的评论,以下是完整的答案:
import os
string1 = "C:/Users/testUser/Program/main.py"
string2 = "C:/Users/testUser/Program/data/somefile.txt"
os.path.relpath(string2, os.path.dirname(string1))
我想你会想要做的是os.path.relpath(字符串2,os.path.dirname(字符串1) )来获得指定的提交者的输出。 – MPlanchard
谢谢你的评论我现在要编辑它:) – Valilutzik