给定一个路径,如“mydir/myfile.txt”,我如何在Python中找到文件的绝对路径?例如,在Windows上,我可能会以:

"C:/example/cwd/mydir/myfile.txt"

当前回答

>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

如果它已经是一个绝对路径也有效:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

其他回答

>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

如果它已经是一个绝对路径也有效:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

今天你也可以使用基于path.py: http://sluggo.scrapping.cc/python/unipath/的unipath包

>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>

我推荐使用这个包,因为它为常见的操作系统提供了一个干净的界面。路径工具。

import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))

注意,expanduser是必要的(在Unix上),如果给定的文件(或目录)名称和位置的表达式可能包含前导~/(波浪号指的是用户的主目录),expandvars负责任何其他环境变量(如$ home)。

Python 3.4+ pathlib的更新实际上回答了这个问题:

from pathlib import Path

relative = Path("mydir/myfile.txt")
absolute = relative.absolute()  # absolute is a Path object

如果您只需要一个临时字符串,请记住,您可以将Path对象与os中的所有相关函数一起使用。路径,当然包括abspath:

from os.path import abspath

absolute = abspath(relative)  # absolute is a str object

你可以使用新的Python 3.4库pathlib。(你也可以使用pip install pathlib为Python 2.6或2.7获取它。)作者写道:“这个库的目的是提供一个简单的类层次结构来处理文件系统路径和用户对它们进行的常见操作。”

在Windows中获取绝对路径:

>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
WindowsPath('C:/Python27/pythonw.exe')
>>> str(p)
'C:\\Python27\\pythonw.exe'

或者在UNIX上:

>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
PosixPath('/opt/python3/bin/python3.4')
>>> str(p)
'/opt/python3/bin/python3.4'

文档在这里:https://docs.python.org/3/library/pathlib.html