exercise16 讀寫文件

需要記住的常用命令:

close -- 關閉文件,相當於編輯器中的File->Save

read -- 讀取文件內容分配給一個變量
readline -- 讀取一行內容
truncate -- 清空文件,小心使用這個命
write(stuff) -- 寫入文件。

python open 使用方法
f=open('/tmp/hello','w')
#open(路徑+文件名,讀寫模式)
#讀寫模式:r只讀,r+讀寫,w新建(會覆蓋原有文件),a追加,b二進制文件.
常用模式如:'rb','wb','r+b'等等

讀寫模式的類型有:

rU 或 Ua 以讀方式打開, 同時提供通用換行符支持 (PEP 278)
w     以寫方式打開,
a     以追加模式打開 (從 EOF 開始, 必要時創建新文件)
r+     以讀寫模式打開
w+     以讀寫模式打開 (參見 w )
a+     以讀寫模式打開 (參見 a )
rb     以二進制讀模式打開
wb     以二進制寫模式打開 (參見 w )
ab     以二進制追加模式打開 (參見 a )
rb+    以二進制讀寫模式打開 (參見 r+ )
wb+    以二進制讀寫模式打開 (參見 w+ )
ab+    以二進制讀寫模式打開 (參見 a+ )





from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file.  Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_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()

3. 上面的代碼有很多重複,想辦法只使用一個target.write()代替上面的6行。
lines = "%s\n%s\n%s\n" % (line1, line2, line3)
target.write(lines)


from sys import argv
script, filename=argv
print "We're going to erase %r."% filename
print "If you don't want that, hit CTRL-C."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target=open(filename, 'w')
target.truncate()
print "Now I'm going to ask you for three lines."
line1=raw_input("line1:")
line2=raw_input("line2:")
line3=raw_input("line3:")
print "I'm going to write these to the file."
lines = "%s\n%s\n%s\n" % (line1, line2, line3)
target.write(lines)
target.write("%s\n%s\n%s\n") %(line1, line2, line3)
print"And finally, we close it."
target.close()




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章