Python 高階文件操作(移動(dòng)、復(fù)制、刪除) - shutil
Python 高階文件操作(移動(dòng)、復(fù)制、刪除) - shutil
導(dǎo)入相關(guān)函數(shù)
from?shutil?import?copyfile,?copytree,?move,?rmtree
文件復(fù)制:
copyfile(src, dst),將 src 文件復(fù)制為 dst,
參數(shù)類型為Path對(duì)象或者字符串。
from?pathlib?import?Path
#?創(chuàng)建一個(gè)測(cè)試文件,寫入內(nèi)容
test_file?=?Path('test.txt')?#?相對(duì)路徑
test_file.write_text('Hello?shutil!')?#?直接寫入,如果不存在會(huì)自動(dòng)創(chuàng)建
test_file?=?test_file.resolve()?#?最好轉(zhuǎn)換為絕對(duì)路徑
print(test_file,test_file.exists())
#?給定一個(gè)新文件路徑
copy_to_file?=?test_file.with_name('copy_to_file.txt')
print(copy_to_file,?copy_to_file.exists())
#?復(fù)制文件
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!
文件移動(dòng):
move(src, dst),可以移動(dòng)文件,或者目錄以及目錄下所有內(nèi)容
#?新建一個(gè)測(cè)試文件夾
test_dir?=?Path('test')
test_dir.mkdir()
test_dir?=?test_dir.resolve()?#?轉(zhuǎn)為絕對(duì)路徑
#?給定一個(gè)新文件路徑
move_to_file?=?test_dir?/?test_file.name
print(move_to_file,move_to_file.exists())
#?移動(dòng)文件
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!
文件夾復(fù)制:
copytree(stc, dst),復(fù)制整個(gè)文件夾目錄樹
#?新建一個(gè)多級(jí)文件夾
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('*')))
#?給定一個(gè)新文件夾路徑
copy_to_tree?=?test_tree.with_name('copy_to_tree')
print(copy_to_tree,copy_to_tree.exists())
#?復(fù)制
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
文件夾移動(dòng):
move(stc, dst)
#?給定一個(gè)路徑,移動(dòng)到?test_dir下
move_to_tree?=?test_dir?/?test_tree.name
print(move_to_tree,?move_to_tree.exists())
#?移動(dòng)
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
刪除測(cè)試文件和目錄
#?test_file.unlink()
copy_to_file.unlink()
move_to_file.unlink()
rmtree(test_dir)
#?rmtree(test_tree)
rmtree(copy_to_tree)