Python 練習實例97

Python 100例 Python 100例

題目:從鍵盤輸入一些字元,逐個把它們寫到磁片檔上,直到輸入一個 # 為止。

程式分析:無。

程式源代碼:

實例(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == '__main__': from sys import stdout filename = raw_input('輸入檔案名:\n') fp = open(filename,"w") ch = raw_input('輸入字串:\n') while ch != '#': fp.write(ch) stdout.write(ch) ch = raw_input('') fp.close()

以上實例輸出結果為:

輸入檔案名:
zaixianfile.txt
輸入字串:
zaixian
zaixian
google
google#

實例中創建了 zaixianfile.txt 檔並向其寫入 zaixian 和 google 兩個字串,查看 zaixianfile.txt 檔內容:

$ cat zaixianfile.txt
zaixiangoogle

Python 100例 Python 100例