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

Linda Hamilton
發布: 2024-10-25 10:39:02
原創
879 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!