《Learn python3 the hard way》ex16 讀寫檔案
阿新 • • 發佈:2018-10-31
作者想讓我們記住的命令:
close- 關閉檔案,就像編輯器中的“檔案->另存為”一樣
read- 讀取檔案內容。你可以把讀取結果賦值給一個變數
readline- 只讀取文字檔案的一行內容
truncate- 清空檔案。清空的時候要當心
write("stuff")-給檔案寫入一些東西。
seek(0)-把讀/寫的位置移到檔案最開頭
from sys import argv #引入argv包
script, filename = argv #拆包一個script一個檔名
print(f"we're going to erase {filename}.") #列印格式化語句
print("If you don't want that, hit CRTL_C(^C).") #說明可以按crtl+c暫停程式
print("If you do want that,hit RETURN.") #列印說明按回車鍵是繼續
input("?") #通過input輸入使用者選擇的
print("Opening the file...") #提示
target = open(filename,'w') #開啟檔案,以寫入的方式,open預設是讀取所以要寫入需修改
print("Truncating the file.Goodbye!") #提示
target.truncate( ) #清空檔案
print("Now I'm going to ask you for three lines.")
#通過3次input將使用者的語句賦值給3個變數
line1 = input("line 1:")
line2 = input("line 2:")
line3 = input("line 3:")
print("I'm going to write these to the file")
target.write(line1)#寫入第一行
target.write("\n") #換行
target.write("line2")#寫入第二行
target.write("\n" )#換行
target.write("line3")#寫入第三行
target.write("\n")#換行
print("And finally. we close it.")
target.close()#關閉檔案