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

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

当前回答

给定一个路径,例如mydir/myfile.txt,我如何在Python中找到文件相对于当前工作目录的绝对路径?

我会这样做,

import os.path
os.path.join( os.getcwd(), 'mydir/myfile.txt' )

返回'/home/ecarroll/mydir/myfile.txt'

其他回答

如果有人正在使用python和linux,并寻找文件的完整路径:

>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file

给定一个路径,例如mydir/myfile.txt,我如何在Python中找到文件相对于当前工作目录的绝对路径?

我会这样做,

import os.path
os.path.join( os.getcwd(), 'mydir/myfile.txt' )

返回'/home/ecarroll/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
>>>

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

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