下面的代碼允許我創建一個目錄,如果它不存在。如何在使用makedirs創建文件夾時覆蓋文件夾?
dir = 'path_to_my_folder'
if not os.path.exists(dir):
os.makedirs(dir)
該文件夾將被程序用來將文本文件寫入該文件夾。但是我想在下一次我的程序打開時從一個全新的空文件夾開始。
如果它已經存在,有沒有辦法覆蓋文件夾(並創建一個新的,具有相同的名稱)?
下面的代碼允許我創建一個目錄,如果它不存在。如何在使用makedirs創建文件夾時覆蓋文件夾?
dir = 'path_to_my_folder'
if not os.path.exists(dir):
os.makedirs(dir)
該文件夾將被程序用來將文本文件寫入該文件夾。但是我想在下一次我的程序打開時從一個全新的空文件夾開始。
如果它已經存在,有沒有辦法覆蓋文件夾(並創建一個新的,具有相同的名稱)?
dir = 'path_to_my_folder'
if os.path.exists(dir):
shutil.rmtree(dir)
os.makedirs(dir)
import shutil
dir = 'path_to_my_folder'
if not os.path.exists(dir):
os.makedirs(dir)
else:
shutil.rmtree(dir) #removes all the subdirectories!
os.makedirs(dir)
怎麼樣?看看shutil的Python
庫!
這也適用。但這是一個相當普遍的模塊?這個代碼需要在很多機器上實現.. – 2012-07-26 00:36:48
@ShankarKumar是的。自從Python 2.4開始,'shutil'是'Python'的一部分。我個人認爲'shutil'比'os'更好,因爲它可以帶來一些簡化。 – cybertextron 2012-07-26 01:16:28
只是說
dir = 'path_to_my_folder'
if not os.path.exists(dir): # if the directory does not exist
os.makedirs(dir) # make the directory
else: # the directory exists
#removes all files in a folder
for the_file in os.listdir(dir):
file_path = os.path.join(dir, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path) # unlink (delete) the file
except Exception, e:
print e
謝謝,這很好!你介意解釋它背後的邏輯嗎?我是一名初學者,所以我儘可能多地學習! – 2012-07-26 00:33:33
儘管如果你在你試圖刪除的目錄中有子目錄,這可能會失敗。然後你想調用'os.walk'來解決這個問題。更簡單的解決方案是使用'shutil.rmtree'。 – inspectorG4dget 2012-07-26 01:45:57
這對競賽條件是否免疫? – 2012-07-26 01:52:58
EAFP (see about it here)版本
import errno
import os
from shutil import rmtree
from uuid import uuid4
path = 'path_to_my_folder'
temp_path = os.path.dirname(path)+'/'+str(uuid4())
try:
os.renames(path, temp_path)
except OSError as exception:
if exception.errno != errno.ENOENT:
raise
else:
rmtree(temp_path)
os.mkdir(path)
歡迎來到堆棧溢出!作爲你的第一個答案,這是我的回顧。當用一個被接受的答案回答一個老問題時,值得強調一下你正在給現有解決方案增加什麼。在這種情況下 - 你能解釋爲什麼你相信這段代碼不受競爭條件的影響嗎?例如 - 如果在調用glob.iglob()之後將文件寫入目錄會發生什麼情況 - 您能描述一下您的解決方案爲何不受競爭條件影響的原因?另外:你可能會考慮解釋EAFP的含義。 *注意:由於原始錯誤* – 2015-02-22 21:01:20
@JRichardSnape,我已重新發布編輯的評論是的,您是對的,這段代碼不會受到競爭條件的影響。在我看來,新版本滿足了這個要求 – 2015-02-23 08:53:14
應該指出,雖然它可能無所謂你們,所有的答案在這裏有競爭條件(雖然它不是真的可能完全消除它們,你可以做得更好,通過使用EAFP)。 – Julian 2012-07-26 01:07:29