How to check if folder exist and create it if it doesn't?
import os
from datetime import datetime
file_path = "F:/TEST--"
if os.path.exists(file_path):
os.rmdir(file_path)
os.makedirs(file_path + datetime.now().strftime('%Y-%m-%d'))
else:
os.makedirs(file_path + datetime.now().strftime('%Y-%m-%d'))
os.path.exists(file_path)
check if the folder TEST--
exists, not if TEST--date
exists, so os.rmdir(file_path)
is never called. Set the folder name before the if
file_path = 'F:/TEST--' + datetime.now().strftime('%Y-%m-%d')
if os.path.exists(file_path):
os.rmdir(file_path)
os.makedirs(file_path)
If the folder contain files you need to delete the first or use shutil
package
shutil.rmtree(file_path)
You can use exist_ok parameter set to True.then if folder exists.python will do nothing.
import os
from datetime import datetime
file_path = "F:/TEST--"
if os.path.exists(file_path):
os.rmdir(file_path)
os.makedirs(file_path + datetime.now().strftime('%Y-%m-%d'),exist_ok=True)
On Python >= 3.5, you can use pathlib.Path.mkdir . Note the exist_ok=True
parameter.
from pathlib import Path
from datetime import datetime
file_path = 'F:/TEST--' + datetime.now().strftime('%Y-%m-%d')
Path(file_path).mkdir(parents=True, exist_ok=True)
Using Pathlib makes your code OS independent and will not break if you decide to move to another OS later on.
PS: It is also advisable to avoid hardcoded paths in your code like F:/TEST--
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.