什么是文件的绝对路径?
的 绝对路径(即。 全路径)和它听起来一样--它是作为函数参数输入的文件的确切路径和位置,在你的机器上的层次结构中。
绝对路径总是从根目录开始,不考虑你的当前工作目录*(CWD*)。
就是这样!所以让我们进入一些代码。
导入Python模块以获得绝对路径
有了200多个核心模块,Python可以做一些惊人的事情。
但是,这也会使初学者感到畏惧。 当我们通过这一个方面时,你应该变得更加清楚,你可以如何浏览你的方式,为你的项目找到特定的工具。
我已经包括了一些链接和例子来帮助你开始。
我们将使用内置的 [os](https://blog.finxter.com/exploring-pythons-os-module/)模块,所以我们需要先导入它。
import os
我们可以在这里只写绝对路径的代码,然后剖析输出,但我想让你更深入地了解Python中可供你使用的东西。
为了得到 Python 中的绝对路径,我们首先检查 [dir()](https://blog.finxter.com/python-dir-a-simple-guide-with-video/)语句在os 模块上的输出。
print(dir(os))
这个简单的代码将给我们提供os 模块的目录。
输出。
# Output:
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_AddedDllDirectory', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_check_methods', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'add_dll_directory', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']
你可以看到它给了我们一个所有可用的子模块和方法的列表。输出中的'path' 子模块是我们接下来用来获取绝对路径的模块。
接下来,我们把os 模块和path 子模块结合起来,得到一个我们可用的方法和函数的目录。
print(dir(os.path)) # os + .path
(如果你对Python非常陌生,在高亮部分前面的哈希值会产生一个注释)
输出。
# Output:
['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_abspath_fallback', '_get_bothseps', '_getfinalpathname', '_getfinalpathname_nonstrict', '_getfullpathname', '_getvolumepathname', '_nt_readlink', '_readlink_deep', 'abspath', 'altsep', 'basename', 'commonpath', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'genericpath', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'relpath', 'samefile', 'sameopenfile', 'samestat', 'sep', 'split', 'splitdrive', 'splitext', 'stat', 'supports_unicode_filenames', 'sys']
它给了我们另一个Python工具的列表,我想突出显示字符串名称abspath 。 你能看到我们是如何边走边构建代码的吗?
提示。os + .path + .abspath
如果你想了解这些工具中任何一个os模块的更多信息,你可以在这里找到。
现在,让我们来了解一下绝对路径
使用abspath()函数
要在Python中获得一个 的绝对路径,使用 函数调用。filename os.path.abspath(filename)
我在这里包含了所有的代码,文件名作为参数输入到abspath() 方法中。
import os
os.path.abspath('Demo_abspath') # Enter file name as a string
关于字符串数据类型的全面教程,请看这个视频。
这段代码的输出。
'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath’
正如我们所看到的,这将返回我用来编写和测试代码的Jupyter笔记本中当前目录的绝对路径。 它被返回为字符串数据类型。
'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'
我在一台Windows机器上,这里有根目录。
'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'
用户,然后是我的用户名,这是接下来的两个步骤。
'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'
文件所在的Jupyter笔记本的文件夹。
'C:\\Users\\tberr\\FinxterProjects1\\Demo_abspath'
最后,是输入到函数中的文件名。
Python绝对路径与相对路径
现在你对Python中的绝对路径有了一些了解,我们应该看看**相对路径,**它 将CWD(当前工作目录)考虑在内。
首先让我们得到CWD。
print(os.getcwd())
输出。
'C:\Users\tberr\FinxterProjects1'
我们得到除了 文件本身以外的所有东西,在这个简单的例子中,它就是 相对路径。
print(os.path.relpath('Demo_abspath'))
输出。
'Demo_abspath'
那么,为什么不使用绝对路径呢? 正如我所说,这是一个非常简单的例子。 当我们进入深度嵌套的目录时,绝对路径会变得非常复杂。
这就是相对路径变得非常有用的地方(而且可以节省一些打字的时间!)。
总结
使用os.path.abspath() 函数来获取绝对路径**,而不**考虑 cwd。
使用os.path.relpath() 函数来获得 与cwd有关的文件的相对路径。
我希望这篇文章对你有帮助,让你对Python中的abspath() 和os 模块有一个初步的认识。 我在第一天就迷上了 Python。 因此,也许这将激励你深入挖掘并探索所有Python能做的令人惊奇的事情--你也会被迷住的!