使用makedirs创建文件夹时,如何覆盖该文件夹(如果已存在)? [英] How to overwrite a folder if it already exists when creating it with makedirs?
本文介绍了使用makedirs创建文件夹时,如何覆盖该文件夹(如果已存在)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码允许我创建目录(如果该目录尚不存在).
The following code allows me to create a directory if it does not already exist.
dir = 'path_to_my_folder'
if not os.path.exists(dir):
os.makedirs(dir)
程序将使用该文件夹将文本文件写入该文件夹.但是,下次我的程序打开时,我想从一个全新的空文件夹开始.
The folder will be used by a program to write text files into that folder. But I want to start with a brand new, empty folder next time my program opens up.
如果该文件夹已经存在,是否有办法覆盖该文件夹(并创建一个具有相同名称的新文件夹)?
Is there a way to overwrite the folder (and create a new one, with the same name) if it already exists?
推荐答案
import os
import shutil
dir = 'path_to_my_folder'
if os.path.exists(dir):
shutil.rmtree(dir)
os.makedirs(dir)
这篇关于使用makedirs创建文件夹时,如何覆盖该文件夹(如果已存在)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文