Python 練習實例99

Python 100例 Python 100例

題目:有兩個磁片檔A和B,各存放一行字母,要求把這兩個檔中的資訊合併(按字母順序排列), 輸出到一個新檔C中。

程式分析:無。

程式源代碼:

#!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == '__main__': import string fp = open('test1.txt') a = fp.read() fp.close() fp = open('test2.txt') b = fp.read() fp.close() fp = open('test3.txt','w') l = list(a + b) l.sort() s = '' s = s.join(l) fp.write(s) fp.close()

運行以上程式前,你需要在腳本執行的目錄下創建 test1.txt、test2.txt 檔。

以上程式執行成功後,打開 test3.txt 檔可以看到內容如下所示:

123456

Python 100例 Python 100例