Python排序输出文件

时间:2018-10-24 08:28:13

标签: python sorting output

nums = range(201,202)
with open('Orig.txt', 'r') as fin:
     with open('out.txt', 'w') as fout:
         for line in fin.readlines():
             line = line.split()

             for i in range(0, len(nums),):
                 line[1] = int(line[1]) + 1
                  #line.append(str(line[1] + 1))
                 line = [str(e) for e in line] 
                 print(line)
                 fout.write(' '.join(line) + '\n')

输入文件

xxx1A   201 18  0   1   0   0   1
xxx2A   201 20  0   1   0   0   1

当前输出看起来像这样

1A  201 18  0   1   0   0   1
1A  202 18  0   1   0   0   1
2A  201 20  0   1   0   0   1
2A  202 20  0   1   0   0   1

我想按第三行或第二行进行排序,即

1A  201 18  0   1   0   0   1
2A  201 20  0   1   0   0   1
1A  202 18  0   1   0   0   1
2A  202 20  0   1   0   0   1

我尝试过的任何排序/反转等

1 个答案:

答案 0 :(得分:0)

您可以使用熊猫:

import pandas as pd
data = pd.read_csv('temp.txt', sep=" ", header=None) #load to pandas
data = data.sort_values(2) #number of column, which you need sort
data.to_csv('new_temp.txt', header=None, index=False, sep=' ') # write to new txt, remember that numerate from 0