How to get an absolute file path in Python

Given a path such as "mydir/myfile.txt" , how do I find the absolute filepath relative to the current working directory in Python? Eg on Windows, I might end up with:

"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:examplecwdmydirmyfile.txt'
>>> 

You could use the new Python 3.4 library pathlib . (You can also get it for Python 2.6 or 2.7 using pip install pathlib .) The authors wrote: "The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them."

To get an absolute path in Windows:

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

Or on UNIX:

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

Docs are here: https://docs.python.org/3/library/pathlib.html

链接地址: http://www.djcxy.com/p/3374.html

上一篇: python能检测到它运行的是哪个操作系统?

下一篇: 如何在Python中获取绝对文件路径