给定一个路径,如“mydir/myfile.txt”,我如何在Python中找到文件的绝对路径?例如,在Windows上,我可能会以:
"C:/example/cwd/mydir/myfile.txt"
给定一个路径,如“mydir/myfile.txt”,我如何在Python中找到文件的绝对路径?例如,在Windows上,我可能会以:
"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
其他回答
>>> 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'
安装一个第三方路径模块(在PyPI上找到),它包装了所有的操作系统。路径函数和其他相关函数变成对象上的方法,可以在任何使用字符串的地方使用:
>>> from path import path
>>> path('mydir/myfile.txt').abspath()
'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
如果你用的是MAC
import os
upload_folder = os.path.abspath("static/img/users")
这将给你一个完整的路径:
print(upload_folder)
将显示以下路径:
>>>/Users/myUsername/PycharmProjects/OBS/static/img/user
今天你也可以使用基于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
>>>
我推荐使用这个包,因为它为常见的操作系统提供了一个干净的界面。路径工具。