Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
which way would be better?
#1
which way would be better (WWWBB)?

1.
from stat import S_ISREG,S_ISDIR,S_ISLNK,S_ISBLK,S_ISCHR
from stat import S_ISFIFO,S_ISSOCK,S_ISPORT,S_ISDOOR,S_ISWHT

def _get_type(a):
    """Get type of file object by path."""
    try:
        s = os.stat(a)
    except FileNotFoundError:
        t='n'
    if   S_ISREG(s.st_mode):t='f'
    elif S_ISDIR(s.st_mode):t='d'
    elif S_ISLNK(s.st_mode):t='l'
    elif S_ISBLK(s.st_mode):t='b'
    elif S_ISCHR(s.st_mode):t='c'
    elif S_ISFIFO(s.st_mode):t='p'
    elif S_ISSOCK(s.st_mode):t='s'
    elif S_ISPORT(s.st_mode):t='P'
    elif S_ISDOOR(s.st_mode):t='D'
    elif S_ISWHT(s.st_mode):t='W'
    else t='?'
    return t
or...

2.
from stat import S_ISREG,S_ISDIR,S_ISLNK,S_ISBLK,S_ISCHR
from stat import S_ISFIFO,S_ISSOCK,S_ISPORT,S_ISDOOR,S_ISWHT

def _get_type(a):
    """Get type of file object by path."""
    try:
        s = os.stat(a)
        t='?'
    except FileNotFoundError:
        return 'n'
    if   S_ISREG(s.st_mode):return 'f'
    elif S_ISDIR(s.st_mode):return 'd'
    elif S_ISLNK(s.st_mode):return 'l'
    elif S_ISBLK(s.st_mode):return 'b'
    elif S_ISCHR(s.st_mode):return 'c'
    elif S_ISFIFO(s.st_mode):return 'p'
    elif S_ISSOCK(s.st_mode):return 's'
    elif S_ISPORT(s.st_mode):return 'P'
    elif S_ISDOOR(s.st_mode):return 'D'
    elif S_ISWHT(s.st_mode):return 'W'
    return '?'
and why?

could performance be considered an issue? would you code this with more spacing? ...more lines?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
You don't need elif here:
    if   S_ISREG(s.st_mode):return 'f'
    elif S_ISDIR(s.st_mode):return 'd'
    elif S_ISLNK(s.st_mode):return 'l'
Use if for each test.
Skaperen likes this post
Reply
#3
Not fan of either ways,i would use dictionary to avoid all if,elif.
import os, sys
from stat import (
    S_ISREG, S_ISDIR, S_ISLNK, S_ISBLK, S_ISCHR,
    S_ISFIFO, S_ISSOCK, S_ISPORT, S_ISDOOR, S_ISWHT
)

def get_type(path):
    """Get type of file object by path."""
    try:
        mode = os.stat(path).st_mode
    except OSError as error :
        return error

    mode_check = {
        S_ISREG: 'regular file', S_ISDIR: 'directory', S_ISLNK: 'l',
        S_ISBLK: 'b', S_ISCHR: 'c', S_ISFIFO: 'p',
        S_ISSOCK: 's', S_ISPORT: 'P', S_ISDOOR: 'D',
        S_ISWHT: 'W'
    }
    for check, type_code in mode_check.items():
        if check(mode):
            return type_code
    return '?'

if __name__ == '__main__':
    # Test
    paths = [
        'G:/div_code',
        'G:/div_code/record.txt'
    ]
    for path in paths:
        print(f"The type of '{path}' is: <{get_type(path)}>")
Output:
The type of 'G:/div_code' is: <directory> The type of 'G:/div_code/record.txt' is: <regular file>
Skaperen likes this post
Reply
#4
Maybe it's worth to reuse existing code ©.

import stat

from pathlib import Path


def filemode(file: str | Path) -> str:
    """
    Returns the first character from stat.filemode() call.
    If FileNotFoundError or PermissionError occurs,  `-` is returned.

    Sometimes stat.filemode() returns `-` for unknown entries.
    Maybe more investigation is required to fully understand when the - occurs.
    """
    try:
        return stat.filemode(Path(file).stat().st_mode)[0]
    except (FileNotFoundError, PermissionError):
        return "-"


path = "/dev/tty1"
print(path, filemode(path))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020