2012-07-26 171 views
16

下面的代码允许我创建一个目录,如果它不存在。如何在使用makedirs创建文件夹时覆盖文件夹?

dir = 'path_to_my_folder' 
if not os.path.exists(dir): 
    os.makedirs(dir) 

该文件夹将被程序用来将文本文件写入该文件夹。但是我想在下一次我的程序打开时从一个全新的空文件夹开始。

如果它已经存在,有没有办法覆盖文件夹(并创建一个新的,具有相同的名称)?

+1

应该指出,虽然它可能无所谓你们,所有的答案在这里有竞争条件(虽然它不是真的可能完全消除它们,你可以做得更好,通过使用EAFP)。 – Julian 2012-07-26 01:07:29

回答

25
dir = 'path_to_my_folder' 
if os.path.exists(dir): 
    shutil.rmtree(dir) 
os.makedirs(dir) 
7
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) 

怎么样?看看shutilPython库!

+0

这也适用。但这是一个相当普遍的模块?这个代码需要在很多机器上实现.. – 2012-07-26 00:36:48

+0

@ShankarKumar是的。自从Python 2.4开始,'shutil'是'Python'的一部分。我个人认为'shutil'比'os'更好,因为它可以带来一些简化。 – cybertextron 2012-07-26 01:16:28

0

只是说

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 
+0

谢谢,这很好!你介意解释它背后的逻辑吗?我是一名初学者,所以我尽可能多地学习! – 2012-07-26 00:33:33

+0

尽管如果你在你试图删除的目录中有子目录,这可能会失败。然后你想调用'os.walk'来解决这个问题。更简单的解决方案是使用'shutil.rmtree'。 – inspectorG4dget 2012-07-26 01:45:57

+0

这对竞赛条件是否免疫? – 2012-07-26 01:52:58

0

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) 
+0

欢迎来到堆栈溢出!作为你的第一个答案,这是我的回顾。当用一个被接受的答案回答一个老问题时,值得强调一下你正在给现有解决方案增加什么。在这种情况下 - 你能解释为什么你相信这段代码不受竞争条件的影响吗?例如 - 如果在调用glob.iglob()之后将文件写入目录会发生什么情况 - 您能描述一下您的解决方案为何不受竞争条件影响的原因?另外:你可能会考虑解释EAFP的含义。 *注意:由于原始错误* – 2015-02-22 21:01:20

+0

@JRichardSnape,我已重新发布编辑的评论是的,您是对的,这段代码不会受到竞争条件的影响。在我看来,新版本满足了这个要求 – 2015-02-23 08:53:14

相关问题