【发布时间】:2021-03-17 14:19:26
【问题描述】:
我有很多由 3 列组成的 csv 文件,如下所示:
fac simile of files: file_1, file_4, file_5, file_7, etc
(All the same file name, != only the final numbers at the end. Them are not consecutive tho as in the
example)
the inside
['357', '29384', '0.0031545741324921135']
['357', '29389', '0.0031545741324921135']
['357', '29526', '0.0368574903844921735']
['357', '35516', '0.0036775741324564665']
['357', '35551', '0.0023554341325646453']
['357', '35639', '0.0064467781324766535']
['357', '36238', '0.0067543874132467543']
['357', '37162', '0.0031545746577921135']
让我们将 3 列命名为 [a,b,c]。我想按 c 对它们进行排序,所以最后一列。我必须阅读所有文件并将所有内容分类为一个巨大的文件。例如,我可以用泡菜。
我的第一个想法是:
import csv
from operator import itemgetter
fn = 1
# N as the max number in the really last file
while fn < N:
newfile = open("file_{fn}.csv","r")
reader = csv.reader(newfile)
file = open("BigSortedFile.csv","w")
for line in sorted(reader, key=itemgetter(2)):
file.write(line)
fn = fn +1
file.close()
#after the loop I think I have to sort again the BigSortedFile.
但它不起作用,因为我需要一个字符串,而不是一行。整个过程怎么做?
【问题讨论】:
标签: python python-3.x csv file sorting