This is what I have:
import os
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
file_path = rf'../database/{names}'
if os.path.exists(file_path) == True:
print('name folders exists')
else:
for name in names:
os.makedirs(os.path.join('../database', name))
I want the code to create the folders for each name in names
list if they do not exist and print name folder exists
if they already exist. But I keep getting a FileExistsError
on the last line. Can someone tell me what I should change in the code to get it to work in the way I want it to?
CodePudding user response:
Where you went wrong was line 3. This line doesn't do what you think it would do:
file_path = rf'../database/{names}'
It creates a single string with all the names added as a list. Instead, you can try something like this:
import os
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
base_path = '../database'
for name in names:
full_path = os.path.join(base_path, name)
if os.path.exists(full_path):
print('name folders exists')
else:
os.mkdir(full_path)
CodePudding user response:
Use the new (introduced in Python 3.4-3.5, so not that new now) Pathlib module instead of os.path
:
from pathlib import Path
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
BASE_PATH = Path('../database')
for name in names:
(BASE_PATH / name).mkdir(exist_ok=True)
From the documentation of pathlib.Path.mkdir
:
If
exist_ok
is true,FileExistsError
exceptions will be ignored, but only if the last path component is not an existing non-directory file.
CodePudding user response:
use a try/except
block to catch and ignore these errors.
eg
try:
os.makedirs(os.path.join('../database', name))
except FileExistsError:
pass
You could even rewrite your code like this:
import os
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
for name in names:
try:
os.makedirs(os.path.join('../database', name))
except FileExistsError:
print('name folders exists')
CodePudding user response:
Your file_path
variable is wrong. It concatenate ../database/
with your list. All elements of your list. The result looks like this:
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
file_path = rf'../database/{names}'
print(file_path)
# ../database/['Abby', 'Betty', 'Bella', 'Peter', 'Jack', 'Sonya']
Instead, do like this:
# Import os define names
for name in names:
path = rf'../database/{name}'
if not os.path.exists(path):
os.mkdir(os.path.join(path))
PS: line 3: if os.path.exists(file_path) == True
The == True
is not necessary because the exists function returns a boolean. Just do if os.path.exists(file_path):