Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

python - 如何在Python中获取绝对文件路径(How to get an absolute file path in Python)

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?

(给定诸如"mydir/myfile.txt"类的路径,我如何找到相对于Python中当前工作目录的文件绝对路径?)

Eg on Windows, I might end up with:

(例如在Windows上,我可能最终得到:)

"C:/example/cwd/mydir/myfile.txt"
  ask by izb translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
>>> 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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...