Question : Merging Files in python

Hi,
I have 2 files that I want to merge. The first file looks something like this:
21:26:16|Some Data 1
23:27:06|Some Data 2
01:28:16|Some Data 3
02:29:10|Some Data 4
03:36:11|Some Data 5

The second file looks something like this:
22:26:16|Some Data A
23:37:00|Some Data B
03:38:06|Some Data C
03:39:00|Some Data D
04:46:01|Some Data E

And the output file should look something like this:
21:26:16|Some Data 1
22:26:16|Some Data A
23:27:06|Some Data 2
23:37:00|Some Data B
01:28:16|Some Data 3
02:29:10|Some Data 4
03:36:11|Some Data 5
03:38:06|Some Data C
03:39:00|Some Data D
04:46:01|Some Data E

How do I do this in python?
Thanks!

Answer : Merging Files in python

Process line by line, advancing file with lesser time:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
import datetime
 
def GetLine(it, rest, out):
  try:
    line = it.next()
  except StopIteration:
    for line in rest:
      out.write(line)
    raise SystemExit
  time = line.split('|', 1)[0]
  return datetime.time(*[int(i) for i in time.split(':')]), line
 
it1 = open('1st file')
it2 = open('2nd file')
out = open('output', 'w')
try:
  t1, d1 = GetLine(it1, it2, out)
  t2, d2 = GetLine(it2, it1, out)
  while True:
    if t1 < t2:
      out.write(d1)
      t1, d1 = GetLine(it1, it2, out)
    else:
      out.write(d2)
      t2, d2 = GetLine(it2, it1, out)
except SystemExit:
  out.close()
  it1.close()
  it2.close()
Open in New Window Select All
Random Solutions  
 
programming4us programming4us