如何获取运算符模块的 sorted 函数来存储数据,以便我可以追加文件?

How do I get the operator module's sorted function to store data so that I can append a file?

我正在尝试将来自 datalist.csv 的数据存储在变量 "sort" 中,以便我可以将数据附加到文件中,但是,它是 returning 空字段.

datalist.csv 的示例文件是

W_A11, 2000-02, Moving average, 59.66666667, 50.92582302, 68.40751031, Injuries, Number, Assault, Validated, Whole pop, All ages, Fatal,
W_A12, 2000-02, Moving average, 1.543343121, 1.317063238, 1.769623003, Per 100,000 people, Age-standardised rate, Assault, Validated, Whole pop, All ages, Fatal,
W_F11B, 2000-02, Moving average, 64.33333333, 55.25710337, 73.40956329, Injuries, Number, Falls, Validated, Whole pop, 0-74 years, Fatal

我不确定要尝试什么。

infile = open("datalist.csv", "r")
    next(infile)
    for line in infile:
        line.strip("'")
        line.strip('"')
    csvfile = csv.reader(infile, delimiter=',')
    csvfile = list(csvfile)
    sort = sorted(csvfile, key= operator.itemgetter(6))
for line in sort:
   print(line)

我希望排序存储来自 datalist.csv 的数据,并将打印语句存储到 return csv,但按第六个索引值组织。它 return 是一个空字段。

这个循环:

for line in infile:
    line.strip("'")
    line.strip('"')

完全消耗 infile(并且对行没有任何影响;strip 不会就地改变数据,而且它可能没有按照你认为的那样做,它只会去掉前导和整行的尾引号,而不是每个字段)。

因此,当您达到:

csvfile = csv.reader(infile, delimiter=',')

reader没有什么可读的。

摆脱循环,离开(经过更多清理,例如使用 with 语句并传递 newline='' 以满足 csv 模块要求):

with open("datalist.csv", newline='') as infile:
    csvfile = csv.reader(infile, delimiter=',')
    next(csvfile)
    sort = sorted(csvfile, key=operator.itemgetter(6))
for line in sort:
    print(line)

它应该可以工作。