第六章:文件系统-shutil:高层文件操作-处理目录树

6.7.3 处理目录树

shutil包含3个函数来处理目录树。要把一个目录从一个位置复制到另一个位置,可以使用copytree()。这个函数会递归遍历源目录树,将文件复制到目标位置。目标目录必须不存在。

import glob
import pprint
import shutil

print('BEFORE:')
pprint.pprint(glob.glob('/tmp/example9/*'))

shutil.copytree('./shutil','/tmp/example9')

print('AFTER:')
pprint.pprint(glob.glob('/tmp/example9/*'))

symlinks参数控制符号链接作为链接复制或文件复制。默认地会将内容复制到新文件。如果这个选项为True,则会在目标树中创建新的符号链接。
运行结果:
在这里插入图片描述
copytree(0接受两个callable参数来控制它的行为。调用ignore参数时要提供复制的各个目录或子目录的名,以及一个目录内容列表。这个函数应当返回待复制元素的一个列表。另外调用copy_function参数来具体复制文件。

import glob
import pprint
import shutil

def verbose_copy(src,dst):
    print('copying\n {!r}'.format(src,dst))
    return shutil.copy2(src,dst)

print('BEFORE:')
pprint.pprint(glob.glob('/tmp/example17/*'))
print()

shutil.copytree(
    './shutil','/tmp/example17',
    copy_function = verbose_copy,
    ignore = shutil.ignore_patterns('*.py'),
    )

print('\nAFTER:')
pprint.pprint(glob.glob('/tmp/example17/*'))

在这个例子中,使用了ignore_patterns()来创建一个ignore函数,要求不复制Python源文件。verbose_copy()首先打印复制文件时的文件名,然后使用copy2()(即默认的复制函数)来建立副本。
运行结果:
在这里插入图片描述
要删除一个目录及其中的内容,可以使用rmtree().

import glob
import pprint
import shutil

print('BEFORE:')
pprint.pprint(glob.glob('/tmp/example/*'))

shutil.rmtree('/tmp/example')

print('\nAFTER:')
pprint.pprint(glob.glob('/tmp/example/*'))

默认地,如果出现错误,则会作为异常抛出,不过如果第二个参数为True,则可以忽略这些错误。可以在第三个参数中提供一个特殊的错误处理函数。

运行结果:
在这里插入图片描述
要把一个文件或目录从一个位置移动到另一个位置,可以使用move()。

import glob
import shutil

with open('example.txt','wt') as f:
    f.write('contens')

print('BEFORE:',glob.glob('example*'))

shutil.move('example.txt','example.out')

print('AFTER :',glob.glob('example*'))

其语义与UNIX命令mv类似。如果源和目标都在同一个文件系统中,则会重命名源文件。否则,源文件会被复制到目标文件,然后被删除。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/88582577
今日推荐