如果你做了上一個(gè)練習(xí)的加分習(xí)題,你應(yīng)該已經(jīng)了解了各種文件相關(guān)的命令(方法/函數(shù))。你應(yīng)該記住的命令如下:
這是你現(xiàn)在該知道的重要命令。有些命令需要接受參數(shù),這對(duì)我們并不重要。你只要記住 write 的用法就可以了。 write 需要接收一個(gè)字符串作為參數(shù),從而將該字符串寫入文件。
讓我們來使用這些命令做一個(gè)簡(jiǎn)單的文本編輯器吧:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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()
|
這個(gè)文件是夠大的,大概是你鍵入過的最大的文件。所以慢慢來,仔細(xì)檢查,讓它能運(yùn)行起來。有一個(gè)小技巧就是你可以讓你的腳本一部分一部分地運(yùn)行起來。先寫 1-8 行,讓它運(yùn)行起來,再多運(yùn)行 5 行,再接著多運(yùn)行幾行,以此類推,直到整個(gè)腳本運(yùn)行起來為止。
你將看到兩樣?xùn)|西,一樣是你新腳本的輸出:
$ python ex16.py test.txt
We're going to erase 'test.txt'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: To all the people out there.
line 2: I say I don't like my hair.
line 3: I need to shave it off.
I'm going to write these to the file.
And finally, we close it.
$
接下來打開你新建的文件(我的是 test.txt )檢查一下里邊的內(nèi)容,怎么樣,不錯(cuò)吧?