Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 353
Lexicon Avatar asked Apr 12 '26 12:04

Lexicon


1 Answers

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.

like image 78
Ben Avatar answered Apr 14 '26 01:04

Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!