简体   繁体   中英

Finding filetype of symlinked file in python

I am trying to figure out a way to find the filetype of a symlinked file in python. The symlinked files are actually .mp3 and .wav files in another directory, but the tools I have tried so far return symlink as the file type as opposed to the actual file type. Does anyone know a way around this?

See:

>>> import magic
>>> mime = magic.open(magic.MIME_TYPE)
>>> mime.load()
0
>>> print mime.file('test.mp3')
inode/symlink

Or:

>>> print subprocess.check_output(['file', '-b', 'test.mp3'])
symbolic link to `../../test/test.mp3'

You can use the os.path.realpath function to resolve the symlink first. It works on regular files too:

$ ln -s foofy bar
$ touch bar
$ python -c '
    from os.path import realpath
    print realpath("bar")
    print realpath("foofy")'

This prints the full path to bar in both cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM