python根据给定的d打印csv数据

2022-05-21 08:35:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python程序,可以从CSV打印出来。代码会要求用户输入开始日期和结束日期,根据此范围程序返回温度。你知道吗

下面是要求用户输入开始日期和结束日期的代码 ( 导入csv 导入日期时间 导入时间 起始日期时间导入日期时间 从datetime导入timedelta

with open('preiction_system.csv', 'r') as csvFile:
    reader = csv.reader(csvFile)

    for row in reader:
        print(row)


ask=input("Enter start  Date\n")

fromDate = time.strptime(ask, "%Y-%m-%d")
start = time.strptime(time.strftime('%Y-%m-%d'),"%Y-%m-%d")


ask=input("Enter End Date\n")

fromDate = time.strptime(ask, "%Y-%m-%d")
end = time.strptime(time.strftime('%Y-%m-%d'),"%Y-%m-%d")

它根据用户输入日期从csv返回行。你知道吗

例如,开始日期为2019-12-01,结束日期为2019-12-05

期望输出:

Date          maxtempC  mintempC    tempC
2019/12/01  29.80    25.35          29.80
2019/12/02  29.78    25.34          29.78
2019/12/03  30.61    24.53          30.61
2019/12/04  32.08    24.75          32.08
2019/12/05  30.42    24.74          30.42

Tags: csvcsvfile代码用户程序inputdatetime时间startreaderaskrowenterstrptime
1条回答
网友
1楼 ·

使用pandas可以

import pandas as pd

df = pd.read_csv('preiction_system.csv')

#start = input("Enter start  Date\n")
#end = input("Enter end  Date\n")

start = "2019/12/02"
end = "2019/12/04"

result = df[ (df['Date'] >= start ) & (df['Date'] <= end) ]

print(result)

result.to_csv('output.csv')

使用csv它可以更长

import csv

# ask before `for` loop
#start = input("Enter start  Date\n")
#end = input("Enter end  Date\n")

start = "2019/12/02"
end = "2019/12/04"

result = []

with open('preiction_system.csv', 'r') as csvFile:
    reader = csv.reader(file_object)

    header = next(reader) # get header
    print(header)
    result.append(result)

    for row in reader:
        if start<= row[0] <= end:
            print(row)
            result.append(row)

# TODO: write result in file