Python中的相对路径 [英] Relative paths in Python

查看:165
本文介绍了Python中的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为工作构建一个简单的帮助程序脚本,该脚本会将代码库中的几个模板文件复制到当前目录.但是,我没有存储模板的目录的绝对路径.我确实有一个来自脚本的相对路径,但是当我调用该脚本时,会将其视为相对于当前工作目录的路径.有没有一种方法可以指定此相对URL来自脚本的位置?

I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relative to the current working directory. Is there a way to specify that this relative url is from the location of the script instead?

推荐答案

在具有脚本的文件中,您想要执行以下操作:

In the file that has the script, you want to do something like this:

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

这将为您提供要查找的文件的绝对路径.请注意,如果您使用的是setuptools,则可能应该使用其包资源API 代替.

This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its package resources API instead.

更新:我在这里回应评论,因此我可以粘贴代码示例. :-)

UPDATE: I'm responding to a comment here so I can paste a code sample. :-)

我是否正确地认为__file__并不总是可用(例如,当您直接运行文件而不是导入文件时)?

Am I correct in thinking that __file__ is not always available (e.g. when you run the file directly rather than importing it)?

当您提到直接运行文件时,我假设您的意思是__main__脚本.如果是这样,在我的系统上似乎不是这种情况(在OS X 10.5.7上为python 2.5.1):

I'm assuming you mean the __main__ script when you mention running the file directly. If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7):

#foo.py
import os
print os.getcwd()
print __file__

#in the interactive interpreter
>>> import foo
/Users/jason
foo.py

#and finally, at the shell:
~ % python foo.py
/Users/jason
foo.py

但是,我确实知道在C扩展名上有一些__file__的古怪之处.例如,我可以在Mac上执行此操作:

However, I do know that there are some quirks with __file__ on C extensions. For example, I can do this on my Mac:

>>> import collections #note that collections is a C extension in Python 2.5
>>> collections.__file__
'/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-
dynload/collections.so'

但是,这在Windows计算机上引发了异常.

However, this raises an exception on my Windows machine.

这篇关于Python中的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆