[英]Searching for keywords in CSV file columns
我需要在CSV文件的一列中搜索特定的关键字,如果找到该关键字,请从整行中获取数据。 我正在使用的文件是我学校的时间表,因此它很大。
import csv
with open('plan.csv', 'rt', encoding='windows 1250') as fileinput:
# In the code below I first create a list of groups, skipping
# duplicates, so that user can later select a group to show it's
# details.
reader = csv.reader(fileinput, delimiter=';')
groups = []
#filling up the list with groups
for row in reader:
if row[12] in groups:
continue
elif row[12] is '':
continue
else:
groups.append(row[12])
# Just to make sure there's something in 'groups'
print(groups[1:])
# Then I'm asking a user to select the group.
# user_choice = input('Group?')
# setting up user_choice to make things simpler for testing
user_choice = '3I4'
# The last part is searching groups column (column index 12) for a
# specific group and if found – print whole row and continue
# the search.
for row in reader:
if row[12] is user_choice:
print(row)
continue
else:
print('not found')
在运行了最后一部分代码后,我根本没有收到控制台输出,也没有收到组的行,也没有“找不到”。
我相信您看不到输出的原因是csv.reader返回一个迭代器,并且您的打印语句之前有一个循环,该循环遍历所有行。 第二次您遍历所有行时,迭代器没有其他行要返回,因此它永远不会进入for循环。 我可能是错的,但是要修复它,请将所有行保存到数组中,或者在第二个for循环之前重新实例化csv.reader。
reader = csv.reader(fileinput, delimiter=';')
该fileinput
您打开已经消耗的第一个for循环。 您需要重新打开文件或重置查找文件的指针。 重新实例化csv.reader
仅不能解决问题,因为它仍使用消耗的fileinput
。 在第一个for循环之后和第二个for循环之前 :
fileinput.seek(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.