Lexicon
Lexicon

Reputation: 2625

Python PATH .is_file() evaluates symlink as a file

In my Python3 program, I take a bunch of paths and do things based on what they are. When I evaluate the following symlinks (snippet):

lrwxrwxrwx  1  513  513        5 Aug 19 10:56 console -> ttyS0
lrwxrwxrwx  1  513  513       11 Aug 19 10:56 core -> /proc/kcore
lrwxrwxrwx  1  513  513       13 Aug 19 10:56 fd -> /proc/self/fd

the results are:

symlink   console -> ttyS0
file      core -> /proc/kcore
symlink   console -> ttyS0

It evaluates core as if it were a file (vs a symlink). What is the best way for me to evaluate it as a symlink vs a file? code below

#!/usr/bin/python3
import sys
import os
from pathlib import Path

def filetype(filein):
    print(filein)
    if Path(filein).is_file():
        return "file"
    if Path(filein).is_symlink():
        return  "symlink"
    else:
        return "doesn't match anything"

if __name__ == "__main__":
file = sys.argv[1]
print(str(file))
print(filetype(file))

Upvotes: 3

Views: 2786

Answers (1)

Ben
Ben

Reputation: 35653

The result of is_file is intended to answer the question "if I open this name, will I open a file". For a symlink, the answer is "yes" if the target is a file, hence the return value.

If you want to know if the name is a symlink, ask is_symlink.

Upvotes: 6

Related Questions