pathlib

Chris Angelico rosuav at gmail.com
Tue Oct 1 03:45:34 EDT 2019


On Tue, Oct 1, 2019 at 3:26 PM DL Neil via Python-list
<python-list at python.org> wrote:
>
> On 1/10/19 1:09 AM, Chris Angelico wrote:
> > I don't think it represents the actual file. If it did, equality would
> > be defined by samefile, NOT by the file name.
> >
> >>>> from pathlib import Path
> >>>> import os
> >>>> open("file1", "w").close()
> >>>> os.link("file1", "file2")
> >>>> Path("file1") == Path("file2")
> > False
> >>>> Path("file1").samefile(Path("file2"))
> > True
> >>>> Path("file1") == Path("file1")
> > True
>
>  >>> f1 = pathlib.Path( "file1" )
>  >>> f2 = pathlib.Path( "file2" )
>  >>> f1 == f2
> False
> ### they are not the same path (by name) - due only to the last character

Correct. The paths are not equal, regardless of whether they represent
the same file.

> Let's try something similar, but the other-way-around:
>
>  >>> f1 = pathlib.Path( "file1" )
>  >>> f1.stat()
> os.stat_result(st_mode=33204, st_ino=1049466, st_dev=64769, st_nlink=1,
> st_uid=1000, st_gid=1000, st_size=0, st_atime=1569903409,
> st_mtime=1569903409, st_ctime=1569903851)
> ### this path exists in the FS
>
>  >>> f1.rename( f2 )
> ### here's a rename operation per the manual!
>  >>> f2.stat()
> os.stat_result(st_mode=33204, st_ino=1049466, st_dev=64769, st_nlink=1,
> st_uid=1000, st_gid=1000, st_size=0, st_atime=1569903409,
> st_mtime=1569903409, st_ctime=1569904293)
> ### f2 is a path which represents a real-world file though
> ### where have we seen those numbers before?

And as you see, f2 now points to that file. So the Path objects
haven't changed, but the underlying file has moved from one to the
other.

The Path does not represent the file; it represents one means of locating it.

One thing that might be nice - although it'd probably be a nightmare
to try to work with across platforms - would be a Path that, rather
than being either absolute (anchored at the root) or relative to the
current directory (not anchored), is relative to a specific other
directory. It'd be described something like "<142857>/path/to/file"
and would reference an open FD. That would give a Path power that a
normal string doesn't have - the power to combine both the arguments
of openat.

ChrisA



More information about the Python-list mailing list