Sha*_*mar 35 python directory overwrite text-files
以下代码允许我创建一个目录(如果它尚不存在).
dir = 'path_to_my_folder'
if not os.path.exists(dir):
os.makedirs(dir)
Run Code Online (Sandbox Code Playgroud)
程序将使用该文件夹将文本文件写入该文件夹.但是我想在下一次打开程序时从一个全新的空文件夹开始.
有没有办法覆盖文件夹(并创建一个具有相同名称的新文件夹),如果它已经存在?
ins*_*get 59
import os
import shutil
dir = 'path_to_my_folder'
if os.path.exists(dir):
shutil.rmtree(dir)
os.makedirs(dir)
Run Code Online (Sandbox Code Playgroud)
cyb*_*ron 16
import os
import shutil
path = 'path_to_my_folder'
if not os.path.exists(path):
os.makedirs(path)
else:
shutil.rmtree(path) # Removes all the subdirectories!
os.makedirs(path)
Run Code Online (Sandbox Code Playgroud)
那个怎么样?看看shutil的Python图书馆吧!
os.path.exists(dir) 建议检查,但可以避免使用 ignore_errors
dir = 'path_to_my_folder'
shutil.rmtree(dir, ignore_errors=True)
os.makedirs(dir)
Run Code Online (Sandbox Code Playgroud)