我的代码应按字母顺序输出名为name
的csv文件列。它出现了list index out of range
。
filename = class_name + ".csv"
csv.register_dialect('pipes', delimiter='|')
with open(filename, 'a',newline='') as fp:
a = csv.writer(fp, delimiter=',')
data=(name,score)
a.writerow(data)
if get_bool_input("Do you wish to view previous results for your class"):
with open(filename, 'r') as f:
reader = csv.reader(f, dialect = 'pipes')
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)
for row in reader:
print (row)
else:
input ("Press any key to exit")
答案 0 :(得分:2)
下面的代码将打开文件,读取标题确定“Name”列的索引,提取所有名称并返回名称的排序列表。
数据文件如下所示:
Name Score
Liam 95
Mason 87
Jacob 67
William 86
Ethan 75
Michael 94
Alexander 84
James 88
Daniel 64
Olivia 100
Sophia 86
Isabella 100
Ava 82
Mia 91
Emily 99
Abigail 82
Madison 91
Charlotte 99
以下是代码:
import csv
filename = 'soc153.csv'
def get_names(filename):
in_list = []
with open(filename, 'r') as f:
reader = csv.reader(f)
header_line = next(reader)
name_column = header_line.index('Name')
for row in reader:
in_list.append(row[name_column])
return(sorted(in_list))
if input("Do you wish to view previous results for your class?") == 'y':
name_list = get_names(filename)
这会在name_list
中生成以下值:
[ '阿比盖尔', “亚历山大”, “艾娃”, “夏洛特”, “丹尼尔”, “艾米丽”, “伊桑”, “伊莎贝拉”, “雅各布”, '詹姆士', '利亚姆', “麦迪逊”, '石匠', “米娅”, “迈克尔”, “奥利维亚, “索菲亚”, '威廉']