1
我有一个文件(file.txt的):如何根据Python中的列对文本文件进行排序?包含以下数据
192.168.10.1/16, 22, 3265, tcp
172.144.32,2/34, 22, 21, udp
10.128.16.234/8, 0, 20, icmp
我需要通过cloumn [0],cloumn [1]和柱[2]
排序此我有一个文件(file.txt的):如何根据Python中的列对文本文件进行排序?包含以下数据
192.168.10.1/16, 22, 3265, tcp
172.144.32,2/34, 22, 21, udp
10.128.16.234/8, 0, 20, icmp
我需要通过cloumn [0],cloumn [1]和柱[2]
排序此我的解决方案是创建这样的元组列表(一个元组每条线):
(data_in_column_of_interest, entire_line)
凡data_in_column_of_interest
是任何数据类型,entire_line
是字符串。
然后就对这个文件列表:包含文件:
def sortLinesByColumn(readable, column, columnt_type):
"""Returns a list of strings (lines in readable file) in sorted order (based on column)"""
lines = []
for line in readable:
# get the element in column based on which the lines are to be sorted
column_element= columnt_type(line.split(',')[column-1])
lines.append((column_element, line))
lines.sort()
return [x[1] for x in lines]
with open('G:/Ftest/data.txt') as f:
# sort the lines based on column 1, and column 1 is type int
sorted_lines = sortLinesByColumn(f, 1, int)
for l in sorted_lines:
print(l)
输入
1, Bob, 123
5, Mary, 112
0, Allen, 2421
1, lucy, 341
输出:一个字符串列表:
0, Allen, 2421
1, Bob, 123
1, lucy, 341
5, Mary, 112
什么是您预期的输出? –
备注:在从函数返回之前,您需要调用'import_file.close()'。 –