常用文件操作函數
- open():打開文件
- read():讀取文件的內容,可以把內容賦值給一個變量。
- close():關閉文件,就像文件編輯器裏面的保存
- readline():讀取文件中的一行
- truncate():清空文件中的內容
- write(‘stuff’):向文件中寫數據’stuff’
代碼:
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()
得到的結果圖:
以及文件data.in中的數據:
我們可以看到在讀取文件的時候在後面加了一個字符’w’。這個符號表示用怎麼得方式讀取文件。一共有三種方式讀取文件(r,w,a):
- r方式:就是隻讀方式,可以在後添加+,b等r+表示可讀寫,rb表示以二進制讀取;
- w方式:就是隻寫方式,可以在後添加+,b等w+表示可讀寫,wb表示以二進制讀取;
- a方式:就是從在文章末尾寫的方式,可以在後田間+,b,意思同上。