Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

python readlink function

tl;dr

def readlinkf(_inpath):
   if os.path.islink(infile):
      return os.path.join(os.path.dirname(_inpath),os.readlink(_inpath))
   else:
      return _inpath

infile=readlinkf(infile)

Explanation

In GNU, there's a fantastic utility named readlink. The main way I use it is to get the full and true path of a file or symlink. For example:

$ ls foo .config/qux
.config/qux  foo
$ readlink -f foo
/home/bgstack15/.config/qux

In python, I wanted to achieve the same thing. it is possible with the os.path.islink and os.readlink functions. Here is my quick function for a readlink -f , since I didn't find a specific implementation that outputs the full path.

Reference

Weblinks

  1. https://stackoverflow.com/questions/11068419/check-if-file-is-symlink-in-python

Online reference

  1. https://docs.python.org/3/library/os.path.html#os.path.islink
  2. https://docs.python.org/3.5/library/os.html#os.readlink

Search expressions

  1. python detect if file is symlink
  2. python readlink

Comments