- close – 關閉文件。跟你編輯器的 文件->保存… 一個意思。
- read – 讀取文件內容。你可以把結果賦給一個變量。
- readline – 讀取文本文件中的一行。
- truncate – 清空文件,請小心使用該命令。
- write(stuff) – 將 stuff 寫入文件。
from sys import argv
scripts,filename = argv
print("We are going to erasing %r" %filename)
print("If you don't want that,hit Ctrl-C(^C)")
print("If you want that,hit Enter")
input('?') #這裏相當於是一個簡單的選擇,看是否要繼續下去,按Enter則繼續
print("Open the file....")
target = open(filename,'w') #首先將filename的內容賦給變量target,這裏多了一個'w',表示write,即寫模式
print("Truncating the file,Goodbye")
target.truncate() #將ex16_sample.txt文件裏面的內容全部清空
print("Now I'm going to ask you for three lines")
line1 = input('line1:') #輸入各行的內容,並將輸入參數賦給line變量
line2 = input('line2:')
line3 = input('line3:')
print("I'm going to write these lines to file")
target.write(line1) #將line變量的內容通過write函數寫到target變量中
target.write('\n')
target.write(line2)
target.write('\n')
target.write(line3)
target.write('\n')
print("And finally,we close it.")
target.close() #結束target變量,相當於保存target變量中的新內容到ex16_sample.txt中去
原本ex16-sample.txt內容如下
執行完腳本之後,變成了對應輸入的內容,如下
思考:
(1)文件中重複的地方太多了。試着用一個 target.write() 將 line1, line2, line3 打印出來,你可以使用字符串、格式化字符、以及轉義字符。
target.write(line1 +’\n’ + line2 +’\n’ + line3) 通過加號拼接
(2)open 對於文件的寫入操作態度是安全第一,所以你只有特別指定以後,它纔會進行寫入操作。
open命令詳細參數表示參考:open命令