【问题标题】:Inputting and printing values from csv in Python在 Python 中从 csv 输入和打印值
【发布时间】:2021-06-17 21:56:55
【问题描述】:

我是 Python 新手,希望有人能在以下方面给我一些指示-

我有一个简单的 .csv 文件,标题为“应付帐款”。我希望在 Python 中阅读的 csv' - 我在下面提供了列名和示例行。

Store ID Account Expiry Date
10229 01/07/2019
87393 31/10/2019
70708 08/11/2021
59565 24/07/2021
67453 07/01/2020

我希望能够从 Store ID 列中输入一个数字到控制台,并让它从 Account Expiry Date 列中打印相应的日期。

然后我想将今天的日期与打印的到期日期进行比较,并根据今天的日期是在帐户到期日期之前还是之后打印“好的”或“帐户已过期”。我是 Python 新手 - 任何帮助或指点都将不胜感激。

【问题讨论】:

  • 本站只针对具体的编程问题,你的问题太宽泛了。刚开始,尝试使用 Python,如果您有特定问题,可以在此处询问您的代码。
  • 我同意@MichaelButscher 的观点,尽管我发现学习编程时最难的事情是知道使用什么术语。因此,您可能需要考虑以下几点:首先,您要解析一个 csv 文件。您可能想查看执行此操作的库。其次,你想让 python 理解日期。您应该查看允许 python 执行此操作的工具/库。只需将两者结合起来,您就有了解决方案! ;)

标签: python csv input


【解决方案1】:

这是一个简单的草稿开始。

import datetime

# reading simple and small csvs are easy by hand
with open("mycsv.csv", encoding="utf-8") as fp:  # open the file
    csv_lines = fp.readlines()  # read all line
csv_lines = [line.split(",") for line in csv_lines[1:]]  # split the lines into 'records'.
                                                         # Note, csv_lines[1:] means we skip the header

input_id = input("Enter store id")  # Read the input from the user

for (store_id, exp_date) in csv_lines:  # we iterate through the data
    if store_id == input_id:  # if the ids are the same
        
        # get today's date and parse datetime from the string. Then, we get the date from the datetime object.
        if datetime.date.today() <= datetime.datetime.strptime(exp_date, "%d/%m/%Y\n").date(): 
            print("okay")
        else:
            print("account has expired")
        break
else:
    print("No record found")

这可能不是这个程序的最佳版本,但它是一个很好的开始,而且一开始可能是最容易理解的。我建议您阅读此代码提供的所有内容。

【讨论】:

  • 非常感谢大家的解释、指点和进一步阅读的建议,非常感谢,并为我的入门奠定了良好的基础 :) 总的来说,我是编码和 IT 的新手正如 Benjamin Chausse 所说,目前对我来说,75% 的战斗是知道如何使用正确的术语提出正确的问题,以便找到可用的资源来构建我自己的解决方案。我真的很感谢你们抽出时间来提供帮助:)
  • 随时!希望您可以使用此代码来学习 Python。尝试代码,熟悉它的结构,并对其进行大量修改,看看修改此代码时会发生什么。另外,如果这个答案有帮助,请考虑接受它作为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 2018-08-08
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
相关资源
最近更新 更多