首頁  >  文章  >  後端開發  >  在Python中如何確定文字檔是否為空?

在Python中如何確定文字檔是否為空?

Linda Hamilton
Linda Hamilton原創
2024-10-25 10:39:02868瀏覽

How can I determine if a text file is empty in Python?

使用 Python 驗證檔案是否存在

在 Python 中,您可以使用 os 模組輕鬆確定文字檔案是否為空。本模組提供了與作業系統互動的各種工具。

要檢查檔案是否為空,可以使用下列步驟:

  1. 匯入 os 模組。
  2. 使用 os.stat("file").st_size 取得檔案大小。
  3. 檢查檔案大小是否等於 0。如果是,則檔案為空;

下面是示範這一點的範例程式碼片段:

<code class="python">import os

# Example file path
file_path = "file.txt"

# Check if the file is empty
if os.stat(file_path).st_size == 0:
    print("The file is empty.")
else:
    print("The file is not empty.")</code>

此程式碼匯入os 模組,擷取檔案的大小,並將其與0 進行比較。如果檔案為空,則列印「The file isempty」;否則,它會列印「檔案不為空。」

以上是在Python中如何確定文字檔是否為空?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn