最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會(huì)員登陸 & 注冊(cè)

Python 高階文件操作(移動(dòng)、復(fù)制、刪除) - shutil

2023-02-19 17:32 作者:梨幾OvO  | 我要投稿

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)


Python 高階文件操作(移動(dòng)、復(fù)制、刪除) - shutil的評(píng)論 (共 條)

分享到微博請(qǐng)遵守國家法律
通海县| 宁德市| 洞头县| 邢台县| 平山县| 米易县| 张家川| 丹寨县| 桐庐县| 张家川| 澎湖县| 长岛县| 夏津县| 阿勒泰市| 义乌市| 太仓市| 金秀| 密云县| 响水县| 错那县| 清水县| 德阳市| 肥西县| 梁河县| 江西省| 集安市| 苍南县| 纳雍县| 米易县| 盘锦市| 驻马店市| 扎兰屯市| 沈阳市| 赞皇县| 莱阳市| 烟台市| 武鸣县| 鹤岗市| 通道| 门头沟区| 和林格尔县|