Latest web development tutorials

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例