如何在Python中获取绝对文件路径

问题描述:

给出一个诸如"mydir/myfile.txt"之类的路径,我如何找到相对于Python中当前工作目录的文件绝对路径?例如.在Windows上,我可能会得到以下结果:

Given a path such as "mydir/myfile.txt", how do I find the file's absolute path relative to the current working directory in Python? E.g. 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'

如果已经是绝对路径,也可以使用:

Also works if it is already an absolute path:

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