snippetpythonCriticalCanonical
How to get an absolute file path in Python
Viewed 0 times
howabsolutefilepathpythonget
Problem
Given a path such as
"mydir/myfile.txt", how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:"C:/example/cwd/mydir/myfile.txt"Solution
>>> 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'Code Snippets
>>> 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'Context
Stack Overflow Q#51520, score: 1542
Revisions (0)
No revisions yet.