13

以供参考。绝对路径是计算机上某个位置的完整路径。相对路径是相对于您当前工作目录 (PWD) 的某个文件的路径。例如:

绝对路径: C:/users/admin/docs/stuff.txt

如果我的 PWD 是C:/users/admin/,那么到的相对路径stuff.txt是:docs/stuff.txt

注意,密码+相对路径=绝对路径。

酷,厉害。现在,我编写了一些脚本来检查文件是否存在。

os.chdir("C:/users/admin/docs") os.path.exists("stuff.txt")

TRUE如果stuff.txt存在则返回并且它可以工作

现在,如果我写,

os.path.exists("C:/users/admin/docs/stuff.txt")

这也返回TRUE

是否有明确的时间我们需要使用其中一个?是否有关于 python 如何查找路径的方法?它会先尝试一个然后再尝试另一个吗?

谢谢!

4

2 回答 2

12

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__ 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__))
于 2017-09-08T03:20:16.753 回答
6

最大的考虑可能是便携性。如果您将代码移动到另一台计算机并且需要访问其他文件,那么其他文件会在哪里?如果它与您的程序位于同一位置,请使用相对地址。如果它将位于相同的绝对位置,请使用绝对地址。

于 2017-06-27T04:22:21.943 回答