在python中对表排序

2024-05-23 17:30:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个6人制足球联赛创建一个排行榜,我正试图按分数列排序,然后在easygui中显示它。到目前为止,我得到的代码是:

data = csv.reader(open('table.csv'), delimiter = ',')
sortedlist = sorted(data, key=operator.itemgetter(7))
with open("Newtable.csv", "wb") as f:
          fileWriter = csv.writer(f, delimiter=',')
          for row in sortedlist:
              fileWriter.writerow(row)
              os.remove("table.csv")
              os.rename("Newtable.csv", "table.csv")
              os.close

数字7与csv文件中的points列有关。我对Newtable有一个问题,Newtable只包含最高点的团队信息和表格.csv显然正被另一个进程使用,因此无法删除。在

如果有人对如何解决这个问题有任何建议,将不胜感激。在


Tags: csvdataostableopen分数row排行榜
2条回答

如果文章中的缩进实际上是脚本中的缩进(而不是复制粘贴错误),那么问题很明显:

os.rename()for循环期间执行(这意味着在CSV文件中每行调用一次!),此时Newtable.csv仍处于打开状态(不是由其他进程而是由脚本本身打开),因此操作失败。在

您不需要关闭f,顺便说一句,with语句会为您处理这个问题。您需要关闭的是data-当调用发生时,该文件仍处于打开状态。在

最后,由于csv对象包含字符串,并且字符串是按字母顺序排序的,而不是按数字排序的(因此"10""2"之前),因此需要根据字符串的数值进行排序,而不是字符串本身。在

你可能想做点什么

with open('table.csv', 'rb') as infile:
    data = csv.reader(infile, delimiter = ',')
    sortedlist = [next(data)] + sorted(data, key=lambda x: int(x[7])) # or float?
    # next(data) reads the header before sorting the rest
with open("Newtable.csv", "wb") as f:
    fileWriter = csv.writer(f, delimiter=',')
    fileWriter.writerows(sortedList)          # No for loop needed :)
os.remove("table.csv")
os.rename("Newtable.csv", "table.csv")

我建议使用^{}

假设输入文件如下:

team,points
team1, 5
team2, 6
team3, 2

你可以:

^{pr2}$

相关问题 更多 >