python 比较pathlib,路径查找一个路径是否是另一个路径的子目录

qv7cva1a  于 2023-02-28  发布在  Python
关注(0)|答案(2)|浏览(629)

我怎样才能知道一个pathlib.path()是否是另一个目录的子目录?
我可以使用pathlib.PurePath()的字符串,但只有在我有完整路径的情况下才能工作。

with zipfile.ZipFile(fname, 'w') as zip:
  for f in files:
    myrelroot = relroot # relative root for this zipfile
    if f"{pathlib.PurePath(relroot)}" not in f"{pathlib.PurePath(f)}":
      myrelroot = None # outside of zipfile so we do not get ..\\..
    try:
      zip.write(f, arcname=os.path.relpath(f, myrelroot))
    except FileNotFoundError as e:
      log.warning(f"file '{f}' not found: {e}")
    else:
      log.info(f"adding {f} to {fname}")
dm7nw8vv

dm7nw8vv1#

你可以用resolve()把它们转换成绝对路径,然后比较parts,这在linux和windows上都有效。

#!/usr/bin/env python3
# CWD: ~/tmp

import pathlib

p1 = pathlib.Path(r"./trash")
p2 = pathlib.Path(r"/home/picobit/tmp/trash/tpath2/tpath2a")

print(p1) # trash
print(p2) # /home/picobit/tmp/trash/tpath2/tpath2a

# Is p2 under p1?
''.join(p1.resolve().parts) in ''.join(p2.resolve().parts) # True

# CWD: C:\Development\TEMP

import pathlib

p1 = pathlib.Path(r".\trash")
p2 = pathlib.Path(r"C:\Development\TEMP\trash\tpath2\tpath2a")

print(p1) # trash
print(p2) # C:\Development\TEMP\trash\tpath2\tpath2a

# Is p2 under p1?
''.join(p1.resolve().parts) in ''.join(p2.resolve().parts) # True
6ljaweal

6ljaweal2#

可以使用pathlib方法is_relative_torelative_to来确定一个路径是否包含在另一个路径中,以及相对路径是什么。

>>> from pathlib import Path
>>> base = Path('/home/username')
>>> p1 = Path('/home/username/Downloads')
>>> p2 = Path('/usr/bin')
>>> p1.is_relative_to(base)
True
>>> p2.is_relative_to(base)
False

然后,您可以将代码重新构造为如下形式:

from pathlib import Path

fname = Path("some/path/to/zipfile.zip")
relroot = fname.parent

with zipfile.ZipFile(fname, 'w') as zip:
  for f in files:
    f = Path(f)
    if not f.exists(): # guard clause protects against non-existent files
        log.warning(f"file '{f}' not found: {e}")
        continue

    # default to use full path
    #   use relative f is a subdirectory of `relroot`
    arcname = f.resolve() 
    if f.is_relative_to(relroot):
        arcname = f.relative_to(relroot)
    
    zip.write(f, arcname=arcname)
    log.info(f"adding {f} to {fname}")

相关问题