简体   繁体   中英

How do I ignore a file that already exists?

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?

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)

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.

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')

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):

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM