csv 函数内部的数据验证- Python

velaa5lx  于 2022-12-06  发布在  Python
关注(0)|答案(1)|浏览(172)

我遇到了一个问题,验证输入是否为有效日期,如果没有返回到问题重试。我想循环通过此标题,并要求为每个项目输入。

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")
nbewdwxp

nbewdwxp1#

几个提示:
1.函数接受参数...
1.全局变量在大多数时候都是一个可怕的想法。像瘟疫一样避免。
将变量传递给函数,以便在函数内部使用它。

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

或者类似的东西。

相关问题