In this example we will show how to use Python to merge two files and output them to a new file.
Source Code
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Please make sure two input files exist
fl = open('D:/python3/demo/t1.txt')
a = fl.read()
fl.close()
fl = open('D:/python3/demo/t2.txt')
b = fl.read()
fl.close()
fl = open('D:/python3/demo/t3.txt', 'w')
c = list(a + b)
c.sort()
s = ''
s = s.join(c)
fl.write(s)
fl.close()
After running the codes above, we can see the new file merged by two files. The content in the new file is sorted alphabetically.
Note: please make sure that two old files have existed before running the codes, otherwise reading content from non-existent files will trigger warnings.