Python Forum

Full Version: Trying to pathlib instead of os.path
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings!
I'm having a hard time justifying why I would use pathlib libraries instead of os.path. Undecided
It is not intuitive and I have a hell of a time trying to use it.
Here is an example, I have a directory with 3 Subdirs and 6 files.
I'm trying to test if an item is a file or directory.
mydir = 'c:\\02'
for esb in os.listdir(mydir) :
    print (esb)
    dr = pathlib.Path(esb)
    print (dr)
regardless if I use 'pathlib.Path" or 'pathlib.PurePath'
both prints are the same.
When I add 'If' to test for Dir/File :
mydir = 'c:\\02'
for esb in os.listdir(mydir) :
    #print (esb)
    dr = pathlib.Path(esb)
    #print (dr)
    item = dr.is_file()
    if item :
        print(f" File") 
    else :
        print(f" Directory")
It prints all 9 items are directories. Confused
Thank you.
You are assuming that if it's not a file that it must be a directory. But that's not the case. It might not exist at all. You've only given the filename to Path, not the entire path. So it's not looking in mydir for the files, it's looking in your current directory. When it's not found, is_file() returns False.

Change line 4 to something like dr = pathlib.Path(mydir, esb)

An alternative that is similar:

import pathlib
import os

mydir = 'C:\\02'
for file_object in pathlib.Path(mydir).iterdir():
    if file_object.is_dir():
        print(f"{file_object} is a Directory")
    elif file_object.is_file():
        print(f"{file_object} is a File")
    else:
        print(f"{file_object} is neither file nor directory.")
bowlofred! You are da man!

I came up with this snipped (see below) it is working but somehow it does not look nice.
hdir = 'c:\\02'
for esb in os.listdir(hdir) :
    ti = os.path.join(hdir,esb)
    tt=pathlib.Path(ti)
    fl =tt.is_dir()
    if fl:
        print(f" it is DIR -> {tt}") 
    else :
        print(f" Is File -> {tt}")
What do you think?
Thank you
(Jun-21-2021, 09:38 PM)tester_V Wrote: [ -> ]I came up with this snipped (see below) it is working but somehow it does not look nice.
You add stuff that is not needed like line 2,3(not pathlib but OS Module).
Look at code to bowlofred if i use it with your print() function.
You should get same output with this code.
import pathlib

mydir = 'c:\\02'
for file_object in pathlib.Path(mydir).iterdir():
    if file_object.is_file():
         print(f" Is File -> {file_object}")
    else:
        print(f" it is DIR -> {file_object}") 
.iterdir() dos the same as os.listdir()
Look at this link as i posted in your other thread Python 3's pathlib Module: Taming the File System.
to snippsat,
I'm confused, man!
Sometimes, for some reason, it looks complicated.
I really appreciate your and everyone help!