Python程式:以讀寫模式開啟檔案並截斷檔案


在Python中,我們可以透過以`w+`模式開啟檔案來以讀寫模式開啟檔案並截斷檔案。截斷檔案是指在開啟檔案之前刪除檔案中的現有內容。在本文中,我們將討論如何以讀寫模式開啟檔案並截斷檔案。

`w+`模式是什麼

Python中的`w+`模式用於以讀寫模式開啟檔案並截斷檔案。當檔案以`w+`模式開啟時,它允許我們讀取和寫入檔案中的資料。如果檔案不存在,`w+`模式將建立一個新檔案並開啟它。

語法

open(‘filename’,’w+’)

上面的`open`方法接受檔名和我們想要開啟檔案的模式。`w+`模式表示應以讀寫模式開啟檔案並截斷檔案。

示例1:使用`w+`模式將資料寫入檔案

在下面的示例中,我們首先使用`open()`函式中的`w+`模式開啟檔案。我們可以使用`write()`方法將資料寫入檔案,並透過將指標移到檔案的開頭然後讀取整個檔案來讀取檔案的內容。

# Open a file in read-write mode with truncating
with open('example.txt', 'w+') as file:
  
   # Write data to the file
   file.write('Hello, World!')
    
   # Move the file pointer to the beginning of the file
   file.seek(0)
    
   # Read the contents of the file
   contents = file.read()
    
   # Print the contents of the file
   print(contents)

輸出

Hello, World!

示例2:使用`w+`模式重寫檔案資料

如果我們再次以`w+`模式開啟同一個檔案並寫入新訊息,例如“This is testing file truncation”,則讀取和列印檔案內容時,輸出將只有新訊息。

# Open a file in read-write mode with truncating
with open('example.txt', 'w+') as file:
  
   # Write data to the file
   file.write('This is testing file truncation!')
    
   # Move the file pointer to the beginning of the file
   file.seek(0)
    
   # Read the contents of the file
   contents = file.read()
    
   # Print the contents of the file
   print(contents)

輸出

This is testing file truncation!

以上兩個示例演示了檔案在以`w+`模式開啟時會被截斷。當我們執行上述程式時,example.txt檔案首先會被截斷,即example.txt檔案的內容會被刪除,然後將新資料寫入檔案。

示例3:使用`w+`模式讀取和寫入檔案資料

在下面的示例中,我們首先以`w+`模式開啟example.txt檔案並讀取檔案的內容。由於我們以`w+`模式開啟它,因此它首先會截斷檔案,即檔案的資料/內容將被清除,檔案為空。因此,讀取檔案後,它輸出一個空字串。然後,我們使用`write()`方法向檔案寫入一些內容,然後再次讀取檔案並列印檔案的內容。

# Open a file in read-write mode with truncating
with open("example.txt", "w+") as file:

# Move the file pointer to the beginning of the file
   file.seek(0)

# Print the contents of the file
   print(file.read())

# Write data to the file
   file.write("This is a new message.\n")

# Move the file pointer to the beginning of the file
   file.seek(0)

# Print the contents of the file
   print(file.read())

輸出

This is a new message.

結論

在本文中,我們討論瞭如何使用檔案的`w+`模式以讀寫模式開啟檔案並截斷檔案。`w+`模式首先清除檔案的內容,然後開啟檔案以讀取或寫入新內容。當處理空檔案以每次寫入新資料時,`w+`模式非常有用。

更新於:2023年4月17日

2K+ 閱讀量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.