打开.txt文件,按升序对第3列进行排序,然后另存为新的.txt文件

时间:2018-01-28 05:16:14

标签: python sorting

我想知道如何打开.txt文件,在为第4列排序后,我可以将其保存为新文件。我知道用于排序的linux终端命令:

sort -k3n  myfile.txt

但如何将其另存为新文件?

如何在python脚本中执行完全相同的操作,就好像numpy.loadtxt将从原始文件中读取,对其进行排序,然后从新的排序文件中再次读取。

# ID x y
    6.60968219252e-05 7.56508909895e-10 40.65
    0.000196142774512 1.90541971372e-09 49.18
    0.000451120770124 3.75884511195e-09 60.78
    9.49736290045e-05 1.08754058315e-09 44.12
    0.000773197066156 5.55965157568e-09 70.64
    0.000395119768811 5.35886928694e-09 48.42
    0.000761797071911 1.1411313874e-08 42.8
    6.13793543105e-05 6.79135943796e-10 36.94
    0.0014257833689 6.69702707603e-09 91.49
    8.02798012773e-05 8.34778117262e-10 43.19

由于

2 个答案:

答案 0 :(得分:2)

Pure python解决方案

>>> import csv
>>> from operator import itemgetter
>>> print(open('sample.csv').read())
1,2,9,3
2,1,4,2
9,2,5,5
3,4,9,7
>>> with open('sample.csv') as fin, open('out.csv', 'w') as fout:
...   csv.writer(fout).writerows(sorted(csv.reader(fin), key=lambda x: float(x[3])))
... 
>>> print(open('out.csv').read())
2,1,4,2
1,2,9,3
9,2,5,5
3,4,9,7

答案 1 :(得分:1)

原始答案

sort -k4n  myfile.txt > newfile.txt

扩大答案。也许与其他答案无关但是...我花了一分钟写它,为什么不分享呢?

with open('source') as fin, with open('destination', 'w') as fout:
    unsorted_lines = [line.split(" ") for line in fin.readlines()]
    sorted_lines = sorted(unsorted_lines, key=lambda coord: coord[2])
    joined_lines = [' '.join(line) for line in sorted_lines]
    for line in joined_lines:
        fout.writelines(line)