Python 打开一个.txt文件,在第3列中按升序排序,然后另存为一个新的.txt文件
我想知道如何打开一个.txt文件,在为第4列排序后,我可以将其另存为一个新文件。我知道用于排序的linux终端命令:Python 打开一个.txt文件,在第3列中按升序排序,然后另存为一个新的.txt文件,python,sorting,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.9054
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
谢谢原始答案
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)
原始答案
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)
纯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
纯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
txt文件包含什么样的数据?“如何将其保存为新文件?”您可以将输出重定向到文件(而不是标准输出),例如,
sort-k4n myfile.txt>outputfile.txt
只有一些带有数字的行和列。您可以显示一个您要排序的文件的示例吗?为什么您说第4列,但您发布了一个带有3列的示例(#ID x y
txt文件有什么类型的数据?“如何将其保存为新文件?”您可以将输出重定向到一个文件(而不是标准输出),例如sort-k4n myfile.txt>outputfile.txt
只是一些带有数字的行和列。您可以显示一个您想要排序的文件的示例吗?为什么您说第4列,但您发布了一个有3列的示例(#ID x y
),您可能应该添加(或提示)同样是Python解决方案,因为它是在OPC中显式询问的,所以您可能也应该添加(或提示)Python解决方案,因为它是在OPC中显式询问的