简体   繁体   English

Python中的相对路径

[英]Relative path in Python

I'm writing some python code to generate the relative path. 我正在编写一些python代码来生成相对路径。 Situation need to be considered: 需要考虑的情况:

  1. Under the same folder. 在同一文件夹下。 I want "." 我想要 ”。” or ".\\", both of tham are ok for me. 或“。\\”,我都可以接受。
  2. Other folder. 其他文件夹。 I want like ".\\xxx\\" and "..\\xxx\\xxx\\" 我想要像“。\\ xxx \\”和“ .. \\ xxx \\ xxx \\”

os.path.relpath() will generate the relative path, but without .\\ at the beginning and \\ in the end. os.path.relpath()将生成相对路径,但在开头不带。\\,在结尾不带\\。 We can add \\ in the end by using os.path.join(dirname, ""). 我们可以使用os.path.join(dirname,“”)最后添加\\。 But i can't figure out how to add ".\\" at the beginning without impacting the first case when they are under the same folder and "..\\xxx\\xxx\\". 但是我不知道如何在开头添加“。\\”而不影响第一种情况(当它们位于同一文件夹和“ .. \\ xxx \\ xxx \\”下)。

It will give you relative path 它会给你相对路径

import os
dir = os.path.dirname(__file__)
filename = os.path.join(dir,'Path')

The relpath() function will produce the ".." syntax given the appropriate base to start from (second parameter). relpath()函数将给出“ ..”语法,并给出从(第二个参数)开始的适当基数。 For instance, supposing you were writing something like a script generator that produces code using relative paths, if the working directory is as the second parameter to relpath() as below indicates, and you want to reference in your code another file in your project under a directory one level up and two deep, you'll get "../blah/blah".. In the case where you want to prefix paths in the same folder, you can simply do a join with ".". 例如,假设您正在编写类似脚本生成器的脚本,该脚本生成器使用相对路径来生成代码,如果工作目录是如下所示的relpath()的第二个参数,并且您想在代码中引用项目下的另一个文件,在上一层和两层下一个目录中,您将获得“ ../blah/blah”。如果要在同一文件夹中添加路径前缀,则只需使用“。”进行连接。 That will produce a path with the correct OS specific separator. 这将产生具有正确的操作系统特定分隔符的路径。

print(os.path.relpath("/foo/bar/blah/blah", "/foo/bar/baz"))
>>> ../blah/blah

print(os.path.join('.', 'blah'))
>>> ./blah    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM