Python读取两个文件内容,按key进行全局排序

2018-01-05  本文已影响0人  狼牙战士

test.py内容:

# 读取file01和file02文件的全部内容,进行全局排序,将结果写入file03
key_list = []
key_val_dic = {}
f1 = open("file01", "r")
f2 = open("file02", "r")
xx = [f1, f2]

for ff in xx:
    for line in ff:
        key, val = line.strip().split('\t')
        key_list.append(int(key))
        key_val_dic[key] = val
f1.close()
f2.close()

f3 = open("file03", "w")
key_list.sort()
for i in range(len(key_list)):
    str1 = str(i) + "\t" + key_val_dic[str(i)]
    f3.write(str1)
    f3.write("\n")
f3.close()

file01文件内容:

0   java
2   java
4   java
6   java
8   java
10  java
12  java
14  java
16  java
18  java
20  java
22  java
24  java
26  java
28  java
30  java
32  java
34  java
36  java
38  java
40  java
42  java
44  java
46  java
48  java
50  java
52  java
54  java
56  java
58  java
60  java
62  java
64  java
66  java
68  java
70  java
72  java
74  java
76  java
78  java
80  java
82  java
84  java
86  java
88  java
90  java
92  java
94  java
96  java
98  java
100 java

file02文件内容:

1   hadoop
3   hadoop
5   hadoop
7   hadoop
9   hadoop
11  hadoop
13  hadoop
15  hadoop
17  hadoop
19  hadoop
21  hadoop
23  hadoop
25  hadoop
27  hadoop
29  hadoop
31  hadoop
33  hadoop
35  hadoop
37  hadoop
39  hadoop
41  hadoop
43  hadoop
45  hadoop
47  hadoop
49  hadoop
51  hadoop
53  hadoop
55  hadoop
57  hadoop
59  hadoop
61  hadoop
63  hadoop
65  hadoop
67  hadoop
69  hadoop
71  hadoop
73  hadoop
75  hadoop
77  hadoop
79  hadoop
81  hadoop
83  hadoop
85  hadoop
87  hadoop
89  hadoop
91  hadoop
93  hadoop
95  hadoop
97  hadoop
99  hadoop

结果文件file03:

全局排序.PNG
上一篇 下一篇

猜你喜欢

热点阅读