學習raw_input和argv是學習讀取文件的前提,你可能不能完全理解這個練習,所以認真學習并檢查。如果不認真的話,很容易刪除一些有用的文件。
這個練習包含兩個文件,一個是運行文件ex15.py,一個是ex15_sample.txt。第二個文件不是腳本文件,只包括一些文本,如下:
This is stuff I typed into a file.It is really cool stuff.Lots and lots of fun to have in here.
我們要做的就是打開這個文件,然后打印文件內容,我們不在代碼中寫死文件名稱,因為我們如果要讀取其他文件的話,就要重新修改代碼,解決這個問題的辦法就是使用argv和raw_input。
from sys import argv script, filename = argv txt = open(filename) print "Here's your file %r:" % filename print txt.read() print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read()
上面的代碼做了一些有意思的事情,讓我們快速的分解一下:
1-3行使用argv取得文件名。第5行使用open命令,現在使用pydoc open看看這個命令的介紹。
第7行打印一行信息,但是第8行有一些新的東西。我們在txt上調用了一個方法。我們通過open方法得到一個file,這個file有一些我們可以調用的方法。使用這些方法的方法就是在file后面加一個.(點),比如txt.read(),就像是說:“嘿,執行讀取命令,沒有任何參數!”
剩下部分大家在加分練習中分析吧。
運行結果
root@he-desktop:~/mystuff# python ex15.py ex15_sample.txt
Here's your file 'ex15_sample.txt':This is stuff I typed into a file.It is really cool stuff.Lots and lots of fun to have in here.Type the filename again:> ex15_sample.txtThis is stuff I typed into a file.It is really cool stuff.Lots and lots of fun to have in here.
下面幾個文件的命令比較常用:
- close -- 關閉文件,相當于編輯器中的File->Save
- read -- 讀取文件內容分配給一個變量
- readline -- 讀取一行內容
- truncate -- 清空文件,小心使用這個命令
- write(stuff) -- 寫入文件。
這些是你應該知道的重要命令,只有write需要提供參數。
讓我們使用這些命令實現一個簡單的文本編輯器。
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, hot 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()
這個程序比較長,所以慢慢來,讓它能運行起來。有個辦法是,先寫幾行,運行一下,可以運行再寫幾行,直到都可以運行。
運行結果
你會看到兩個東西,一個是程序的輸出:
root@he-desktop:~/mystuff# 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, hot RETURN.?Opening the file...Truncating the file. Goodbye!!Now I'm going to ask you for three lines.line 1: Hi!line 2: Welcome to my blog!line 3: Thank you!I'm going to write these to the file.And finally, we close it.
還有就是你新建立的文件,打開看看吧。