if i added a csv file name inccorrectly i wnat to show error message entered csv file does not exist please write the correct csv file name.how it make?
class Command(BaseCommand):
help = 'Load a company csv file into the database'
def add_arguments(self, parser):
parser.add_argument('filename.csv', type=str)
def handle(self, *args, **options ):
if Company.objects.exists():
print("Data already loaded!!")
with open('companies.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
create= Company.objects.get_or_create(
name=row[0],
hr_name=row[1],
hr_email=row[2],
hr_verified=row[3],
user_id=row[4],
primary_phone=row[5],
comments=row[6],
)
CodePudding user response:
This is more of a Python question than a Django question. You can do it with a try/catch
throwing FileNotFoundError
exception when an incorrect file is given.
def handle(self, *args, **options ):
if Company.objects.exists():
print("Data already loaded!!")
try:
with open('companies.csv', 'r') as file:
reader = csv.reader(file)
....
except FileNotFoundError:
# Yoour error message goes here
CodePudding user response:
- You can use a try except:
try:
with open(filename, "r") as file:
# ...
except FileNotFoundError as e:
print("Please write the correct cvs file name")
- You can check if it exists the file:
import os
if not os.path.exists(filename):
print("Please write the correct csv file name")