Python内部的数据验证



我在验证输入是否为有效日期时遇到了一个问题,如果没有返回问题进行重试。我想循环浏览这个标题,并要求输入每个项目。

header = [employee_id,name,address,ssn,date_of_birth,job_title,start_date,end_date]

除了标题之外,CSV是空的,因为我通过这个程序将这些行附加到中。我希望date_validator((适用于DOB、start_date和end_date,但到目前为止,我可以让它验证输入是否错误,它只是不会再次返回并要求输入。任何帮助都将不胜感激!谢谢

import csv
import datetime
def add_employee():
global date_answer
list = []
for i in range(len(header)):
var = header[i]
answer1 = input('Input Employees {}:'.format(var))
if "date" in header[i]:
date_answer = answer1
date_validater()
list.append(answer1)
with open('employees.csv','a',newline="") as f_object:
writer = csv.writer(f_object)
writer.writerow(list)
f_object.close()
print()
def date_validater():
# input date
date_string = date_answer
date_format = '%m/%d/%Y'
try:
dateObject = datetime.datetime.strptime(date_string, date_format)
print(dateObject)
except ValueError:
print("Incorrect data format, should be MM/DD/YYYY")

几个提示:

  1. 函数接受参数
  2. 全球化在大多数时候都是一个可怕的想法。像躲避瘟疫一样躲避

将变量传递给函数,以便在函数中使用它。

import csv
import datetime
def add_employee(header):
list = []
for i in range(len(header)):
var = header[i]
answer1 = input('Input Employees {}:'.format(var))
if "date" in header[i]:
date_validater(answer1)
list.append(answer1)
with open('employees.csv','a',newline="") as f_object:
writer = csv.writer(f_object)
writer.writerow(list)
f_object.close()
print()
def date_validater(date_string):
# input date
date_format = '%m/%d/%Y'
try:
dateObject = datetime.datetime.strptime(date_string, date_format)
print(dateObject)
except ValueError:
print("Incorrect data format, should be MM/DD/YYYY")

或者类似的东西。。。

相关内容

  • 没有找到相关文章

最新更新