如何在Python中获取绝对文件路径 [英] How to get an absolute file path in Python

查看:327
本文介绍了如何在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'

这篇关于如何在Python中获取绝对文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆