教程

Python 3 Basic Python Advanced Tkinter Python Modules JavaScript Python Numpy Git Matplotlib PyQt5 Data Structure Algorithm

貼士文章

Rust Python Pygame Python Python Tkinter Batch PowerShell Python Pandas Numpy Python Flask Django Matplotlib Plotly Docker Seaborn Matlab Linux Git C Cpp HTML JavaScript jQuery TypeScript Angular React CSS PHP Java Go Node.js Kotlin Csharp Ruby Arduino MongoDB MySQL Postgres R VBA Scala Raspberry Pi

函數參考

Python Pandas Numpy

EOF 代表 End Of File 。這是程式中使用者無法再讀取資料的地方。這意味著程式讀取整個檔案直到結束。此外,當到達 EOF 或檔案末尾時,將返回空字串作為輸出。因此,使用者需要知道檔案是否處於其 EOF。

本教程介紹了在 Python 中找出檔案是否處於其 EOF 的不同方法。

在 Python 中使用 file.read() 查詢檔案尾

file.read() 方法是一個內建的 Python 函式,用於讀取給定檔案的內容。如果 file.read() 方法返回一個空字串作為輸出,這意味著檔案已達到其 EOF。

with open("randomfile.txt", "r") as f:
    while True:
        file_eof = file_open.read()
        if file_eof == "":
            print("End Of File")
            break

請注意,當我們在程式開始時呼叫 open() 函式開啟檔案時,我們使用 "r" 作為僅讀取檔案的模式。最後,我們使用 if 條件語句來檢查最後返回的輸出是否為空字串。

在 Python 中使用帶有 while 迴圈的 readline() 方法查詢檔案結尾

file.readline() 方法是另一個內建的 Python 函式,用於讀取一個完整的文字檔案行。

Python 中的 while 迴圈是一個迴圈,它迭代程式碼塊中的給定條件,直到給定條件為真。當迭代次數未知時使用此迴圈。

while 迴圈與 readline() 方法一起使用有助於重複讀取給定文字檔案中的行。

file_path = "randomfile.txt"
file_text = open(file_path, "r")
a = True
while a:
    file_line = file_text.readline()
    if not file_line:
        print("End Of File")
        a = False
file_text.close()

當文字檔案中沒有可供 readline() 方法讀取的文字時, while 迴圈將停止迭代。

在 Python 中使用 Walrus 運算子查詢檔案尾

Walrus 運算子是 Python 3.8 中的一個新運算子。它由 := 表示。這個運算子基本上是一個賦值運算子,用於分配 True 值,然後立即列印它們。

file = open("randomfile.txt", "r")
while f := file.read():
    process(f)
file.close()

此處,True 值是 read() 函式將從文字檔案中讀取的字元。這意味著一旦檔案完成,Walrus 運算子將停止列印。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.

LinkedIn