這個(gè)練習(xí)包含兩個(gè)文件,一個(gè)是運(yùn)行文件ex15.py,一個(gè)是ex15_sample.txt。第二個(gè)文件不是腳本文件,只包括一些文本,如下:
This is stuff I typed into a file. It is really cool stuff. Lots and lots of fun to have in here.
我們要做的就是打開(kāi)這個(gè)文件,然后打印文件內(nèi)容,我們不在代碼中寫(xiě)死文件名稱,因?yàn)槲覀內(nèi)绻x取其他文件的話,就要重新修改代碼,解決這個(gè)問(wèn)題的辦法就是使用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命令,現(xiàn)在使用pydoc open看看這個(gè)命令的介紹。
第7行打印一行信息,但是第8行有一些新的東西。我們?cè)趖xt上調(diào)用了一個(gè)方法。我們通過(guò)open方法得到一個(gè)file,這個(gè)file有一些我們可以調(diào)用的方法。使用這些方法的方法就是在file后面加一個(gè).(點(diǎn)),比如txt.read(),就像是說(shuō):“嘿,執(zhí)行讀取命令,沒(méi)有任何參數(shù)!”
剩下部分大家在加分練習(xí)中分析吧。
運(yùn)行結(jié)果
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.txt This is stuff I typed into a file. It is really cool stuff. Lots and lots of fun to have in here.
下面幾個(gè)文件的命令比較常用:
這些是你應(yīng)該知道的重要命令,只有write需要提供參數(shù)。
讓我們使用這些命令實(shí)現(xiàn)一個(gè)簡(jiǎn)單的文本編輯器。
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(" ") target.write(line2) target.write(" ") target.write(line3) target.write(" ") print "And finally, we close it." target.close()
這個(gè)程序比較長(zhǎng),所以慢慢來(lái),讓它能運(yùn)行起來(lái)。有個(gè)辦法是,先寫(xiě)幾行,運(yùn)行一下,可以運(yùn)行再寫(xiě)幾行,直到都可以運(yùn)行。
運(yùn)行結(jié)果
你會(huì)看到兩個(gè)東西,一個(gè)是程序的輸出:
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.
還有就是你新建立的文件,打開(kāi)看看吧。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com