對文件操做流程python
現有文件以下linux
Beautiful is better than ugly. 優美勝於醜陋 Explicit is better than implicit. 明瞭勝於晦澀 Simple is better than complex. 簡單賽過複雜 Complex is better than complicated. 複雜賽過凌亂 Flat is better than nested. 扁平勝於嵌套 Sparse is better than dense. 間隔勝於緊湊 Readability counts. 可讀性很重要 Special cases aren't special enough to break the rules. 即便假借特例的實用性之名,也不違背這些規則 Although practicality beats purity. 雖然實用性次於純度 Errors should never pass silently. 錯誤不該該被無聲的忽略 Unless explicitly silenced. 除非明確的沉默 In the face of ambiguity, refuse the temptation to guess. 當存在多種可能時,不要嘗試去猜想 There should be one-- and preferably only one --obvious way to do it. 應該有一個,最好只有一個,明顯能作到這一點 Although that way may not be obvious at first unless you're Dutch. 雖然這種 方式可能不容易,除非你是python之父 Now is better than never. 如今作總比不作好 Although never is often better than *right* now. 雖然過去從未比如今好 If the implementation is hard to explain, it's a bad idea. 若是這個實現不容易解釋,那麼它確定是壞主意 If the implementation is easy to explain, it may be a good idea. 若是這個實現容易解釋,那麼它極可能是個好主意 Namespaces are one honking great idea -- let's do more of those! 命名空間是一種絕妙的理念,應當多加利用
基本操做windows
f=open('import this.txt') first_line = f.readline() print('first line:',first_line) #讀一行,結果爲first line: Beautiful is better than ugly. data = f.read() print(data) #閱讀整個文件 f.close() #關閉文件
打開文件的模式有:less
"+" 表示能夠同時讀寫某個文件ide
"U"表示在讀取時,能夠將 \r \n \r\n自動轉換成 \n (與 r 或 r+ 模式同使用)ui
"b"表示處理二進制文件(如:FTP發送上傳ISO鏡像文件,linux可忽略,windows處理二進制文件時需標註)this
with語句idea
爲了不打開文件後忘記關閉,能夠經過管理上下文自動關閉,即:spa
with open('import this.txt','r') as f: ...