Python pathlib Module

move all text files to an archive directory

import glob
import os
import shutil

for file_name in glob.glob('*.txt'):
    new_path = os.path.join('archive', file_name)
    shutil.move(file_name, new_path)

.cwd() (Current Working Directory) and .home() (your user’s home directory)

import pathlib
pathlib.Path.cwd()
pathlib.Path.home()

Creating Paths

pathlib.Path(r'C:\Users\gahjelle\realpython\file.txt')

or

pathlib.Path.home() / 'python' / 'scripts' / 'test.py'

or

pathlib.Path.home().joinpath('python', 'scripts', 'test.py')

finds all headers in a Markdown file and prints them

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

or

path = pathlib.Path.cwd() / 'test.md'
with path.open(mode='r') as fid:
    headers = [line.strip() for line in fid if line.startswith('#')]
print('\n'.join(headers))

properties

path = pathlib.Path('test.md')
path.resolve()
path
# PosixPath('/home/gahjelle/realpython/test.md')
path.name
# 'test.md'
path.stem
# 'test'
path.suffix
# '.md'
path.parent
# PosixPath('/home/gahjelle/realpython')
path.parent.parent
# PosixPath('/home/gahjelle')
path.anchor
#'/'
path.parent.parent / ('new' + path.suffix)
# PosixPath('/home/gahjelle/new.md')

count how many files there are of each filetype in the current directory

import collections
collections.Counter(p.suffix for p in pathlib.Path.cwd().iterdir())
#Counter({'.md': 2, '.txt': 4, '.pdf': 2, '.py': 1})

only counts filetypes starting with p

import collections
collections.Counter(p.suffix for p in pathlib.Path.cwd().glob('*.p*'))
#Counter({'.pdf': 2, '.py': 1})

Display a Directory Tree

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

Create a Unique File Name

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')

Python 3’s pathlib Module: Taming the File System

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值