>>> 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'
23
您可以使用新的Python 3.4库 pathlib . (您也可以使用 pip install pathlib 获取Python 2.6或2.7 . )作者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."
要在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'
9 回答
如果它已经是绝对路径也可以工作:
您可以使用新的Python 3.4库
pathlib
. (您也可以使用pip install pathlib
获取Python 2.6或2.7 . )作者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."要在Windows中获取绝对路径:
或者在UNIX上:
文件在这里:https://docs.python.org/3/library/pathlib.html
更好的是,安装path.py模块,它将所有
os.path
函数和其他相关函数包装到一个对象的方法中,该对象可以在任何使用字符串的地方使用:今天你也可以使用基于
path.py
的unipath
包:http://sluggo.scrapping.cc/python/unipath/我建议使用这个包,因为它提供a clean interface to common os.path utilities .
我更喜欢使用glob
以下是如何列出当前文件夹中的所有文件类型:
这里是如何列出当前文件夹中的所有(例如).txt文件:
以下是如何列出所选目录中的所有文件类型:
希望这能帮助你
如果你在Mac上
这会给你一个完整的路径:
将显示以下路径:
如果有人使用python和linux并寻找文件的完整路径: