讀取檔案慢_練習 16 - 讀寫檔案 - Learn Python 3 The Hard Way
阿新 • • 發佈:2021-01-17
技術標籤:讀取檔案慢
練習 16. 讀寫檔案
如果你做了上一節的附加練習,你應該看到了所有的命令(commands,modules,functions),你可以把這些命令施加給檔案。以下是一些我想讓你記住的命令:
close - 關閉檔案,就像編輯器中的 “檔案->另存為”一樣。 read - 讀取檔案內容。你可以把讀取結果賦給一個變數。 readline - 只讀取文字檔案的一行內容。 truncate - 清空檔案。清空的時候要當心。 write('stuff') - 給檔案寫入一些“東西”。 seek(0) - 把讀/寫的位置移到檔案最開頭。
這些都是你需要知道的一些非常重要的命令。其中一些要用到引數,但是我們暫且不去重點關注。你只需要記住 write
讓我們用這些命令做一個小小的編輯器:
ex16.py
1 from sys import argv 2 3 script, filename = argv 4 5 print(f"We're going to erase {filename}.") 6 print("If you don't want that, hit CTRL-C (^C).") 7 print("If you do want that, hit RETURN.") 8 9 input("?") 10 11 print("Opening the file...") 12 target = open(filename, 'w') 13 14 print("Truncating the file. Goodbye!") 15 target.truncate() 16 17 print("Now I'm going to ask you for three lines.") 18 19 line1 = input("line 1: ") 20 line2 = input("line 2: ") 21 line3 = input("line 3: ") 22 23 print("I'm going to write these to the file.") 24 25 target.write(line1) 26 target.write("n") 27 target.write(line2) 28 target.write("n") 29 target.write(line3) 30 target.write("n") 31 32 print("And finally, we close it.") 33 target.close()
這真是一個很大的檔案,可能是你輸入過的最大的檔案了。所以慢一點,寫完檢查一下,然後再執行。你也可以寫一點執行一點,比如先執行 1-8 行,然後再多執行 5 行,然後再多幾行,直到所有的都完成和運行了。
你應該看到
事實上你應該看到兩樣東西,首先是你新指令碼的輸出結果:
練習 16 會話
$ python3.6 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: Mary had a little lamb line 2: Its fleece was white as snow line 3: It was also tasty I'm going to write these to the file. And finally, we close it.
現在,用編輯器開啟你建立的檔案(比如我的是 test.txt),檢查一下是不是對的。
附加練習
1. 如果你理解不了這個練習,回過頭去按照給每行加註釋的方法再過一遍,註釋能幫助你理解每一行的意思,至少讓你知道你不理解的地方在哪裡,然後動手去查詢答案。
2. 寫一個類似於上個練習的指令碼,使用read
和argv
來讀取你剛剛建立的檔案。
3. 這個練習中有太多的重複,試著用一個target.write()
命令來列印 line1、line2、line3,你可以使用字串、格式字串和轉義字元。
4. 弄明白為什麼我們要用一個'w'
作為一個額外的引數來開啟。提示:通過明確說明你想要寫入一個檔案,來安全地開啟它。
5. 如果你用w
模式開啟檔案,那你還需要target.truncate()
嗎? 讀一讀 Python 的 open 函式檔案,來搞明白這個問題。
常見問題
truncate()
對於 'w'
引數來說是必須的嗎? 詳見附加練習 5。
'w'
到底是什麼意思? 它真的只是一個有字元的字串,來表示檔案的一種模式。如果你用了 'w'
,就代表你說“用 ‘write’ 模式開啟這個檔案。此外還有 'r'
表示 read 模式,'a'
表示增補模式,後面還可能加一些修飾符(modifiers)。
我能對檔案使用哪些修飾符? 目前最重要的一個就是 +
,你可以用 'w+'
, 'r+'
以及 'a+'
。這樣會讓檔案以讀和寫的模式開啟,取決於你用的是那個符號以及檔案所在的位置等。
如果只輸入 open(filename)
是不是就用 'r'
(讀)模式開啟? 是的,那是 open()
函式的預設值。