何时在 Python 中使用绝对路径与相对路径 [英] When to use Absolute Path vs Relative Path in Python
问题描述
供参考.绝对路径是计算机上某个位置的完整路径.相对路径是相对于当前工作目录 (PWD) 的某个文件的路径.例如:
For reference. The absolute path is the full path to some place on your computer. The relative path is the path to some file with respect to your current working directory (PWD). For example:
绝对路径:C:/users/admin/docs/stuff.txt
如果我的 PWD 是 C:/users/admin/
,那么 stuff.txt
的相对路径将是:docs/stuff.txt代码>
If my PWD is C:/users/admin/
, then the relative path to stuff.txt
would be: docs/stuff.txt
注意,密码+相对路径=绝对路径.
Note, PWD + relative path = absolute path.
很酷,很棒.现在,我写了一些脚本来检查文件是否存在.
Cool, awesome. Now, I wrote some scripts which check if a file exists.
os.chdir("C:/users/admin/docs")os.path.exists("stuff.txt")
如果 stuff.txt
存在并且它有效,则返回 TRUE
.
This returns TRUE
if stuff.txt
exists and it works.
现在,如果我写的话,
os.path.exists("C:/users/admin/docs/stuff.txt")
这也返回 TRUE
.
是否有明确的时间需要使用一个而不是另一个?有没有关于python如何查找路径的方法?它是先尝试一个然后另一个吗?
Is there a definite time when we need to use one over the other? Is there a methodology for how python looks for paths? Does it try one first then the other?
谢谢!
推荐答案
如果你不知道用户将从哪里执行脚本,最好使用 os 计算用户系统上的绝对路径
和 __file__
.
If you don't know where the user will be executing the script from, it is best to compute the absolute path on the user's system using os
and __file__
.
__file__
是在每个 Python 脚本上设置的全局变量,它返回包含它的 *.py
文件的相对路径.
__file__
is a global variable set on every Python script that returns the relative path to the *.py
file that contains it.
import os
my_absolute_dirpath = os.path.abspath(os.path.dirname(__file__))
这篇关于何时在 Python 中使用绝对路径与相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!