何时在Python中使用绝对路径与相对路径 [英] When to use Absolute Path vs Relative Path in Python

查看:366
本文介绍了何时在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

注意,PWD +相对路径=绝对路径.

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")

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?

谢谢!

推荐答案

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

The biggest consideration is probably portability. If you move your code to a different computer and you need to access some other file, where will that other file be? If it will be in the same location relative to your program, use a relative address. If it will be in the same absolute location, use an absolute address.

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

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