繁体   English   中英

如何在列表中插入键值对并写入 csv 文件

[英]How to insert a key value pair on a list and write on a csv file

我是 Python 的新手,我被赋予了公司 HRIS 的任务。 因此,我从 raw.csv 文件中编写了一个代码,该文件将通过过滤所有其他数据来重写,并确保将列出一个人的 IN 和 OUT 的第一个实例。 如何在同一行的列表中插入或 append 一个人的时间?

employeeInfo2 = {'Name': employeeName, 'Date': employeeDate, 'Status': employeeStatus}
        if employeeInfo2 not in employeeProfile:
            employeeProfile.append(employeeInfo2)

当我尝试将这行代码放在上述代码的下方时,时间在 csv 文件中显示为新行或写入新行。

employeeProfile.append({'Time': employeeTime})
import csv
import string
import datetime
from dateutil.parser import parse
from collections import OrderedDict

employeeProfile = []
with open('newDTR.csv', 'r') as csv_file:
    employee = csv.DictReader(csv_file, delimiter=",")

    for employeeList in employee:
        stringDate = employeeList['Date/Time']
        employeeName = employeeList['Name']
        employeeStatus = employeeList['Status']
        dateTimeObject = datetime.datetime.strptime(stringDate,  '%d/%m/%Y %I:%M:%S %p')
        employeeDate = dateTimeObject.strftime("%d/%m/%Y")
        employeeTime = dateTimeObject.strftime("%H:%M:%S")
        parsedTimeOut = parse(employeeTime)
        expected = parsedTimeOut + datetime.timedelta(hours=9)
        timeOut = expected.time()
        employeeInfo2 = {'Name': employeeName, 'Date': employeeDate, 'Status': employeeStatus}
        if employeeInfo2 not in employeeProfile:
            employeeProfile.append(employeeInfo2)


with open('fixedDTR.csv', mode='w', newline='', encoding='utf8') as new_csv_file:
    fieldnames = ['Name', 'Date', 'Status', 'Time', 'Expected Time Out']
    csv_writer = csv.DictWriter(new_csv_file, fieldnames=fieldnames)
    csv_writer.writeheader()
    for b in employeeProfile:
        print(b)
        csv_writer.writerow(b)

我期待employeeTime 将与每一行数据对齐,但事实并非如此。 可能是因为employeeProfile.append({'Time':employeeTime}) 在新行上。 最好的方法应该是什么?

输出文件

好吧,看看你的代码,当你从employeeProfile 写b 时,没有和插入时间。

简单地说,当您使用 csv_write.writerow(b) 时,这将自动 go 在 csv 文件中下降 1 行。 您可以 append 您的时间密钥存储在员工档案中的字典。

employeeInfo2 = {'Name': employeeName, 'Date': employeeDate, 'Status': employeeStatus}

if employeeInfo2 not in employeeProfile:
            employeeInfo2["Time"] = employeeTime # or whatever you wanted in the field 
            employeeProfile.append(employeeInfo2)

这会将 Time 列添加到您的 dict,然后由 csv_writer.writerow 很好地编写。

根据你的 output 我猜你是这样写的时间:

csv_writer.writerow(b) 
csv_writer.writerow(times)

时代是您对时代的口述。 这会导致偏移,因为 writerow 会在 csv 的每一行中添加一个换行符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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