跳轉到內容

Python 程式設計入門/Python 程式設計 - 處理檔案

來自華夏公益教科書,開放的書籍,開放的世界

7. 檔案

[編輯 | 編輯原始碼]

Python 提供了更多輸入和輸出功能。“print”語句是最簡單的產生輸出的方法。

Python 直譯器從終端讀取輸入時有兩種方法,即

  1. raw_input

此命令無論輸入的是表示式還是其他內容,都會將終端上的所有內容讀取為輸入,並返回一個字串。

  1. 輸入

input 命令將表示式作為常規的 Python 表示式進行評估,並將其作為輸入。

以下示例突出了 raw_input 和 input 之間的區別。

   >>> a=raw_input("enter your test here : ")
   enter your test here : new
   >>> a
   'new'
   >>> print a
   new
   >>> b=raw_input("enter your python expression :")
   enter your python expression : (1,2,3)
   >>> print a
   new
   >>> print b
   (1,2,3)
   >>> c=input("enter your text here :")
   enter your text here :"sunami"
   >>> print c
   sunami
   >>> d=input("enter your text here :")
   enter your text here :(1,2,3)
   >>> print d
   (1, 2, 3)
   >>> print type(d)
   <type 'tuple'>
   >>>e=input("enter your text here :")
   enter your text here :[x*x for x in range(5)]
   >>> print e
   [0, 1, 4, 9, 16]
   >>> f=raw_input("enter your python expression :")
   enter your python expression :[x*x for x in range(5)]
   >>> print f
   [x*x for x in range(5)]
   >>>

7.1. 開啟和關閉檔案

[編輯 | 編輯原始碼]

到目前為止,我們一直在輸入終端寫入,並在終端獲得輸出。現在讓我們進一步瞭解如何讀取和寫入檔案。Python 提供了大量用於讀取和寫入檔案的函式,這些檔案可以是文字檔案或資料檔案。檔案操作命令是透過檔案物件完成的。

檔案操作函式列表已作為示例突出顯示,並在註釋中提供了說明。可以開啟檔案以供讀取、寫入或追加現有文字。

“open”函式開啟一個檔案,該檔案可用於讀取、寫入或追加資料。為了執行上述任何功能,必須先開啟每個檔案。

   >>> myfile=open("example.txt", "w")
   >>> myfile.write("Oh my god!! I just opened a new file ! \n")
   >>> myfile.write("I typed in a whole lot of text \n")
   >>> myfile.write("Thank god, its ending ! \n")
   >>> myfile.close()
   >>>

請記住關閉檔案,然後檢查實際檔案是否包含已寫入檔案的內容。現在,讓我們繼續讀取剛剛寫入的檔案的內容。

   >>> myfile=open("example.txt", "r")
   >>> for a in myfile.readlines():
           print a
   Oh my god!! I just opened a new file ! 
   I typed in a whole lot of text 
   Thank god, its ending ! 
   >>>
   >>> myfile.close()
   >>> myfile=open("example.txt", "w")
   >>> myfile.write("Start of a new chapter ! \n")
   >>> myfile.write("The second line in charter! \n")
   >>> myfile.close()
   >>> myfile=open("example.txt", "a")
   >>> myfile.write("Oh my god!! I just opened a new file ! \n")
   >>> myfile.write("I typed in a whole lot of text \n")
   >>> myfile.write("Thank god, its ending ! \n")
   >>> myfile.close()
   >>> myfile=open("example.txt", "r")
   >>> print myfile
   <open file 'example.txt', mode 'r' at 0x02115180>
   >>> myfile.close()

Python 模組“os”提供用於執行檔案處理操作(如重新命名和刪除檔案)的方法。要獲取當前工作目錄,請執行以下操作。

   >>> import os
   >>> print os.getcwd()
   C:\Users\Desktop\Projects\Upwork
   I already have an existing file named example.txt which I will rename using the Python os utility functions.
   >>>os.rename("example.txt", "sample.txt")
華夏公益教科書