Python 高阶文件操作(移动、复制、删除) - shutil

Python 高阶文件操作(移动、复制、删除) - shutil

导入相关函数

from shutil import copyfile, copytree, move, rmtree

文件复制:

copyfile(src, dst),将 src 文件复制为 dst,

参数类型为Path对象或者字符串。

from pathlib import Path

# 创建一个测试文件,写入内容
test_file = Path('test.txt') # 相对路径
test_file.write_text('Hello shutil!') # 直接写入,如果不存在会自动创建
test_file = test_file.resolve() # 最好转换为绝对路径
print(test_file,test_file.exists())

# 给定一个新文件路径
copy_to_file = test_file.with_name('copy_to_file.txt')
print(copy_to_file, copy_to_file.exists())

# 复制文件
copyfile(test_file, copy_to_file)

print(copy_to_file.exists())
print(test_file.read_text())
print(copy_to_file.read_text())

D:\PycharmProjects\untitled\python代码分享\test.txt True
D:\PycharmProjects\untitled\python代码分享\copy_to_file.txt False
True
Hello shutil!
Hello shutil!

文件移动:

move(src, dst),可以移动文件,或者目录以及目录下所有内容

# 新建一个测试文件夹
test_dir = Path('test')
test_dir.mkdir()
test_dir = test_dir.resolve() # 转为绝对路径

# 给定一个新文件路径
move_to_file = test_dir / test_file.name
print(move_to_file,move_to_file.exists())

# 移动文件
move(test_file, move_to_file)

print(move_to_file.exists())
print(move_to_file.read_text())
D:\PycharmProjects\untitled\python代码分享\test\test.txt False
True
Hello shutil!

文件夹复制:

copytree(stc, dst),复制整个文件夹目录树

# 新建一个多级文件夹
test_tree = Path('test_tree')
dirs = test_tree/ 'test_child'/ 'xxx_folder'
dirs.mkdir(parents=True)
test_tree = test_tree.resolve()
print(test_tree, test_tree.exists())
print(list(test_tree.rglob('*')))

# 给定一个新文件夹路径
copy_to_tree = test_tree.with_name('copy_to_tree')
print(copy_to_tree,copy_to_tree.exists())

# 复制
copytree(test_tree, copy_to_tree)

print(copy_to_tree.exists())

D:\PycharmProjects\untitled\python代码分享\test_tree True
[WindowsPath('D:/PycharmProjects/untitled/python代码分享/test_tree/test_child'), WindowsPath('D:/PycharmProjects/untitled/python代码分享/test_tree/test_child/xxx_folder')]
D:\PycharmProjects\untitled\python代码分享\copy_to_tree False
True

文件夹移动:

move(stc, dst)

# 给定一个路径,移动到 test_dir下
move_to_tree = test_dir / test_tree.name
print(move_to_tree, move_to_tree.exists())

# 移动
move(test_tree, test_dir)

print(move_to_tree, move_to_tree.exists())
D:\PycharmProjects\untitled\python代码分享\test\test_tree False
D:\PycharmProjects\untitled\python代码分享\test\test_tree True

删除测试文件和目录

# test_file.unlink()
copy_to_file.unlink()
move_to_file.unlink()
rmtree(test_dir)
# rmtree(test_tree)
rmtree(copy_to_tree)
2 个赞

666,牛呀

快点睡觉~