在python中查找csv文件所在行的位置

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

我有下面的代码写使用Pandas库:

# function : check for time
def checktime(reportedtime, scheduledtimestart, scheduledtimeend):
    if scheduledtimestart <= reportedtime <= scheduledtimeend:
        return "Yes"
    else:
        return "No"

df.loc[sub_df.index, 'Access Valid'] = checktime(time_date, schedule_start_date, schedule_end_date)

df.to_excel(current_directory + '/files/updated_report.xlsx', index=False)

df是主/原始 Dataframe 。而sub_df是修改/过滤后的 Dataframe 。Access Valid是我试图向其附加值的列。
该程序检查用户time_date发出请求的时间是否在其schedule_start_dateschedule_end_date之间。然后,它将列Access Valid下的单元格更新为yesno

问题

我被要求修改我的代码,并使用import csv库,而不是import pandas,由于大小,但我无法确定指定行的位置,以便将Access Valid附加到csv文件并将其导出为excel文件。
用户列表:

user; scheduled start date; scheduled end date;
test1; 2022-09-01 00:00:00; 2022-09-30 23:59:59;
test2; 2022-09-01 00:00:00; 2022-09-14 23:59:59;

示例文件结构(文件包含超过1000个请求):

time; user; Access Valid
2022-09-20 09:09:00; test1; 
2022-09-21 05:00:00; test2;

所需的文件输出:

time; user; Access Valid
2022-09-20 09:09:00; test1; yes
2022-09-21 05:00:00; test2; no
7ivaypg9

7ivaypg91#

使用csv,代码将如下所示:

import csv

with open(FILE_WITH_ACCESS_DATA) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=';')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            #header
            print(f'{";".join(row)}')
        else:
            #content
            print(f'{row[0]};{row[1]}; ' + checktime(time_date, schedule_start_date, schedule_end_date))
        line_count += 1

相关问题