简体   繁体   English

如何对 csv 文件进行排序以仅在文件中获取一行?

[英]how to sort a csv file to only get one row within the file?

This is what my code looks like这就是我的代码的样子

pd.set_option('expand_frame_repr', False)
inventory_data = pd.read_csv('inventory_list_1.csv')
search_item = input('Enter the name of the item your looking for')
find_item = inventory_data['Item_Name'].astype(str).str.contains(serch_item)
print (find_item)
inventory_data.to_csv('inventory_list_1.csv', index=False, quoting=1)

This is an example of the CSV file with the top row being the header这是 CSV 文件的示例,顶行是 header

[ITEM NAME 1], [QUANTITY 1], [PRICE 1]
pencil           3             4
pen              5             5

I want to be able to type in pen for the input我希望能够输入笔输入

search_item = input('Enter the name of the item your looking for')

and get the following row back并取回下一行

pen              5             5

I'm kinda at a loss as how to do this我对如何做到这一点有点不知所措

you could use the row function and iterrows您可以使用行 function 和 iterrows

just like this像这样

for index, row in df.iterrows():
    print(row['c1'], row['c2'])

Output: 
   10 100
   11 110
   12 120

source: How to iterate over rows in a DataFrame in Pandas来源: 如何在 Pandas 中的 DataFrame 中迭代行

Use this用这个

for (row,rowSeries) in inventory_data.iterrows():
       print(row,rowSeries)

Here's a sample program to read the contents of csv file and check for an item.这是一个示例程序,用于读取 csv 文件的内容并检查项目。

inventory_list_1.csv

item,quantity,price
pencil,5,10
pen,5,5`

Sample Program示例程序

# import csv module
import csv
# Ask for user input
search_item = input('Enter the name of the item your looking for: ')
# read data from csv file
filePointer = open('inventory_list_1.csv')
input_file = csv.DictReader(filePointer)
# set a flag
found = False
# iterate through the contents and check for search_item
for row in input_file:
    if row['item'] == search_item:
       print(row['item'],row['quantity'],row['price'])
       found = True
       break
if not found:
    print(f"Item '{search_item}'' not found!")

# release
filePointer.close()

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

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