文件目錄初始化工作(清空文件夾)

在整個(gè)軟件開發(fā)項(xiàng)目中,可能涉及到對(duì)文件目錄的讀取,寫入操作,初始化工作不可或缺的就是對(duì)文件進(jìn)行規(guī)范化操作,下面提供一段文件初始化的代碼。

```python

import os

import shutil

filename = 'test'

? ? output_path_abs = os.path.join(os.getcwd(), filename)

? ? if os.path.exists(output_path_abs) is False:

? ? ? ? # 當(dāng)路徑不存在時(shí)候,創(chuàng)建路徑

? ? ? ? os.makedirs(output_path_abs)

? ? else:

? ? ? ? # 當(dāng)路徑存在時(shí)候,進(jìn)行清空操作

? ? ? ? for i in os.listdir(output_path_abs):

? ? ? ? ? ? if os.path.isdir(os.path.join(output_path_abs, i)):

? ? ? ? ? ? ? ? shutil.rmtree(os.path.join(output_path_abs, i))

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? os.remove(os.path.join(output_path_abs, i))


```

代碼的功能注釋也有寫了,就是文件夾不在的時(shí)候就創(chuàng)建,在的時(shí)候就清空,從而保證這個(gè)文件路徑存在并且無其他內(nèi)容。

在清空部分用到兩種方法:rmtree和remove,一種用于刪除文件夾,另一種就是刪除文件,兩者都不能混著用。

當(dāng)然,在這段代碼中也有比較暴力的做法,就是文件夾如果存在就刪除后再重建

```python

import os

import shutil

filename = 'test'

? ? output_path_abs = os.path.join(os.getcwd(), filename)

? ? if os.path.exists(output_path_abs) is False:

? ? ? ? # 當(dāng)路徑不存在時(shí)候,創(chuàng)建路徑

? ? ? ? os.makedirs(output_path_abs)

? ? else:

shutil.rmtree(output_path_abs)

os.makedirs(output_path_abs)

```

可以省幾行代碼,但我們就了解不到那兩種刪除的方法和差異了,看你個(gè)人的喜好吧。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容