【问题标题】:How do I get the operator module's sorted function to store data so that I can append a file?如何获取操作员模块的排序功能来存储数据,以便我可以附加文件?
【发布时间】:2019-07-09 04:36:50
【问题描述】:

我正在尝试将 datalist.csv 中的数据存储在变量“sort”中,以便我可以将数据附加到文件中,但是,它返回的是一个空字段。

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)

我希望 sort 存储 datalist.csv 中的数据,并让 print 语句返回 csv,但由第六个索引值组织。而是返回一个空字段。

【问题讨论】:

    标签: python python-3.x csv file-io


    【解决方案1】:

    这个循环:

    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)
    

    它应该可以工作。

    【讨论】:

    • 这完全解决了我的问题!非常感谢 ShadowRanger。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    相关资源
    最近更新 更多