python pathlib

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python pathlib相关的知识,希望对你有一定的参考价值。

>>> path = pathlib.Path('test.md')

>>> import pathlib
>>> pathlib.Path.cwd()
PosixPath('/home/gahjelle/realpython/')

>>> pathlib.Path.home() / 'python' / 'scripts' / 'test.py'
>>> pathlib.Path.home().joinpath('python', 'scripts', 'test.py')
PosixPath('/home/gahjelle/python/scripts/test.py')

path = pathlib.Path.cwd() / 'test.md'

>>> path.resolve()
PosixPath('/home/gahjelle/realpython/test.md')
>>> path.resolve().parent == pathlib.Path.cwd()
False

>>> path
PosixPath('/home/gahjelle/realpython/test.md')
>>> path.name
'test.md'
>>> path.stem
'test'
>>> path.suffix
'.md'
>>> path.anchor
'/'
>>> path.parent
PosixPath('/home/gahjelle/realpython')
>>> path.parent.parent
PosixPath('/home/gahjelle')

>>> path
PosixPath('/home/gahjelle/realpython/test001.txt')
>>> path.with_suffix('.py')
PosixPath('/home/gahjelle/realpython/test001.py')
>>> path.replace(path.with_suffix('.py'))

if not destination.exists():
  source.replace(destination)

with destination.open(mode='xb') as fid:
  fid.write(source.read_bytes())
def tree(directory):
  print(f'+ {directory}')
  for path in sorted(directory.rglob('*')):
    depth = len(path.relative_to(directory).parts)
    spacer = '    ' * depth
    print(f'{spacer}+ {path.name}')
    
>>> tree(pathlib.Path.cwd())
+ /home/gahjelle/realpython
  + directory_1
    + file_a.md
  + directory_2
    + file_a.md
    + file_b.pdf
    + file_c.py
  + file_1.txt
  + file_2.txt
>>> from datetime import datetime

>>> time, file_path = max((f.stat().st_mtime, f) for f in directory.iterdir())

>>> print(datetime.fromtimestamp(time), file_path)
2018-03-23 19:23:56.977817 /home/gahjelle/realpython/test001.txt

>>> max((f.stat().st_mtime, f) for f in directory.iterdir())[1].read_text()
<the contents of the last modified file in directory>
def unique_path(directory, name_pattern):
  counter = 0
  while True:
    counter += 1
    path = directory / name_pattern.format(counter)
    if not path.exists():
      return path

path = unique_path(pathlib.Path.cwd(), 'test{:03d}.txt')

with open(path, mode='r') as fid:
    headers = [line.strip() for line in fid if line.startswith('#')]
print('\n'.join(headers))

with path.open(mode='r') as fid:
    ...

.read_text(): open the path in text mode and return the contents as a string.
.read_bytes(): open the path in binary/bytes mode and return the contents as a bytestring.
.write_text(): open the path and write string data to it.
.write_bytes(): open the path in binary/bytes mode and write data to it.

以上是关于python pathlib的主要内容,如果未能解决你的问题,请参考以下文章

13-Python-pathlib库使用

python 笔记:Pathlib

Python 3.4+:扩展 pathlib.Path

python笔记72 - 使用pathlib替代os.path

python pathlib学习

python pathlib