gpt4 book ai didi

python - 根据用户输入的标准从 .csv 打印行

转载 作者:太空宇宙 更新时间:2023-11-04 02:24:51 24 4
gpt4 key购买 nike

我是 python 的新手,正在寻找有关我正在处理的任务的指导。

我正在导入一个如下表所示的 csv 文件。

invoice_id,customer_first_name,customer_last_name,part_number,quantity,total

18031,Hank,Scorpio,367,1,2.63
54886,Max,Power,171,3,50.79
19714,Jonathan,Frink,179,2,7.93
19714,Jonathan,Frink,378,2,32.34
22268,Gil,Gunderson,165,2,47.15
87681,Lionel,Hutz,218,1,50.83
84508,Lurleen,Lumpkin,257,1,81.95
34018,Lionel,Hutz,112,3,88.88
34018,Lionel,Hutz,386,3,86.04
34018,Lionel,Hutz,216,1,53.54
66648,Patty,Bouvier,203,3,70.47

我只想打印基于用户输入的标准的每一行。例如,如果用户输入 lname,然后输入 Hutz,将打印出以下内容。

87681,Lionel,Hutz,218,1,50.83
34018,Lionel,Hutz,112,3,88.88
34018,Lionel,Hutz,386,3,86.04
34018,Lionel,Hutz,216,1,53.54
4 records found.

这就是我目前所拥有的...

salesdatafile= None
while True:
salesdatafilename=input("Enter the name of the file:")
try:
salesdata= open(salesdatafilename, 'r')
break
except FileNotFoundError:
print("{0} was not found".format ( salesdatafilename ))

search=input("Do you want to search by invoice id or lname? Please type id or lname: ")
idsearch=salesdata.readline()

if search== 'id':
idnumber=print(int(input('Please enter Id to search: ')))
while idsearch != '':
if idsearch== idnumber:
print(idsearch)

else:
lname=print(input('Please enter your last name: '))
while idsearch != '':
if idsearch== lname:
print(idsearch)

打印出来的都是用户输入的lname或id。

最佳答案

Python 有一个内置的 csv 模块,您应该使用它。查看下面的示例代码:

import csv
salesdatafilename = r"path/to/file.txt"
data = csv.reader(open(salesdatafilename))
last_name_to_look_for = "Lionel"
for invoice_id, customer_first_name, customer_last_name, part_number, quantity, total in data:
if customer_last_name == last_name_to_look_for:
print(invoice_id, customer_first_name, customer_last_name, part_number, quantity, total)

关于python - 根据用户输入的标准从 .csv 打印行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50662220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com