1. 程式人生 > >笨辦法16讀寫文件

笨辦法16讀寫文件

put pan sys div 是否 cat fcm bsp 用戶

代碼如下:

 1 #coding:utf-8
 2 from sys import argv
 3 
 4 script, filename = argv
 5 
 6 print "We‘re going to erase %r." %filename #提示語句,告知用戶將抹掉文件
 7 print "If you don‘t want that, hit CTRL-C (^C)." #提示語句,停止操作的按鍵
 8 print "If you do want that, hit RETURN." #提示語句,繼續操作的按鍵
 9 
10 raw_input("?") #讓用戶輸入是否要繼續操作
11 12 print "Opening the file..." #提示語句,正在打開文件 13 target = open(filename, w) #將打開的文件清空並賦值給target,w不能大寫 14 15 print "Truncating the file. Goodbye!" #提示語句,正在清空文件 16 target.truncate() #執行清空文件操作#truncate()其實是不需要的,因為open的參數是w 17 18 print "Now I‘m going to ask you for three lines." #提示語句 19 20 line1 = raw_input("
line 1:") #輸入第一行的內容 21 line2 = raw_input("line 2:") #輸入第二行的內容 22 line3 = raw_input("line 3:") #輸入第三行的內容 23 24 print "I‘m going to write these to the file." #提示語句 25 26 target.write(line1) #寫入第一行的內容 27 target.write("\n") #寫入換行符 28 target.write(line2) 29 target.write("\n") 30 target.write(line3) 31 target.write("
\n") 32 33 print "And finally, we close it." #提示關閉文件 34 target.close() #關閉(保存)文件

運行結果:
技術分享

新增的文件內容:
技術分享

註:
‘w’:以只寫模式打開。若文件存在,則會自動清空文件,然後重新創建;若文件不存在,則新建文件。使用這個模式必須要保證文件所在目錄存在,文件可以不存在。該模式下不能使用read*()方法


加分練習2:代碼如下

1 print "Please enter your filename, and I‘ll read it."
2 
3 filename = raw_input(">")
4 txt = open(filename)
5 print txt.read()

運行結果:
技術分享


加分練習3:寫了兩種方法

1 #target.write(line1+"\n"+line2+"\n"+line3) #變量不需加引號,字符串需要加雙引號#a+b參考第6課
2 target.write("%s\n%s\n%s" % (line1, line2, line3)) #這裏如果用%r,文件的每行字符會有引號

加分練習4:找出為什麽我們需要給 open 多賦予一個 ‘w’ 參數。提示: open 對於文件的寫入操作態度是安全第一,所以你只有特別指定以後,它才會進行寫入操作。
因為默認open只能讀取不能寫入,所以要寫入內容就必須加入’w’參數。
truncate()其實是不需要的,因為open的參數是w

笨辦法16讀寫文件