標籤:rom 讀寫 put test 關閉 使用 檔案 print and
一個簡單的文字編輯器
# -*- coding: utf-8 -*-from sys import argv # 從sys模組匯入argv函數,#「argv」是「argument variable」參數變數的簡寫形式。一般在命令列調用的時候由系統傳遞給程式。# 一般在命令列調用的時候由系統傳遞給程式。script, filename = argv # 利用argv函數,把 argv 中的東西解包,將所有的參數依次賦予左邊的變數名print "We‘re going to erase %r." % filename # 列印檔案名參數print "If you don‘t want that, hit CTRL-C (^C)." # 提示輸入CTRL+C就退出程式print "If you do want that, hit RETURN." printprint "Here is the original file: "printtxt = open(filename) # 使用open函數開啟檔案,並把內容存到txt變數中print txt.read() # 讀取txt的內容並列印出來,這一塊是為了讀取未清除檔案內容並寫入其他內容之前的內容raw_input("?")print "Opening the file..."target = open(filename, ‘w‘) # 以寫入模式開啟檔案print "Truncating the file. Goodbye!"target.truncate() # 用truncate函數清除檔案內容print "Now I‘m going to ask you for three lines."print#line1 = raw_input("Line 1: ") # 寫入三行內容,儲存到line1,line2和line3的變數中txt1 = open(filename, ‘w‘)txt1.write (‘This is a test.\nReally, it is.‘)txt1.close()printprint "I‘m going to write these to the file."printtarget.write(line2) # 使用write函數把line1變數中target.write("\n") # 使用write函數寫入一個分行符號target.write(line2) #使用write函數把line2變數中target.write("\n") # 使用write函數寫入一個分行符號target.write(line3) #使用write函數把line3變數中target.write("\n") # 使用write函數寫入一個分行符號printprint "And finally, we close it."target.close() # 關閉檔案filename1 = raw_input("input a filename: ")filename1_open = open(filename1) # 開啟檔案print "Here is the new file content: "printprint filename1_open.read() # 讀取新的檔案內容print "close opened file..."filename1_open.close() # 關閉檔案
Python學習16:讀寫檔案