Python 檔案 isatty() 方法



Python 檔案isatty() 方法檢查檔案流是否是互動式的。如果檔案連線到“tty”型別的裝置,則檔案流被認為是互動式的。這就是此方法名稱“is a tty”的含義。

“tty”裝置是“Teletypewriter”(電傳打字機)裝置的縮寫。它是一種用於執行 I/O 操作的輸入裝置,即它是一個控制終端和 Python 程式之間通訊的介面。

語法

以下是 Python 檔案isatty() 方法的語法:

fileObject.isatty();

引數

此方法不接受任何引數。

返回值

如果檔案連線到(與終端裝置關聯)tty(類似)裝置,則此方法返回 true,否則返回 false。

示例

以下示例顯示了 Python 檔案 isatty() 方法的用法。在這裡,我們使用檔案物件以“寫入二進位制”模式 (wb) 開啟檔案。然後,我們呼叫此建立的檔案物件上的方法來檢查檔案是否連線到 tty 裝置。

# Open a file
fo = open("foo.txt", "wb")
print("Name of the file:", fo.name)

ret = fo.isatty()
print("Return value:", ret)

# Close opened file
fo.close()

執行上述程式時,會產生以下結果:

Name of the file: foo.txt
Return value: False

示例

但是,如果目錄中不存在該檔案,則該方法將引發 FileNotFoundError。

# Open a file
fo = open("tutorials.txt", "r")
print("Name of the file:", fo.name)

val = fo.isatty()
print("Is a tty?", val)

# Close opened file
fo.close()

讓我們編譯並執行上面的程式,輸出如下所示:

Traceback (most recent call last):
  File "d:\Tutorialspoint\Programs\Python File Programs\isattydemo.py", line 2, in 
    fo = open("tutorials.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'tutorials.txt'
python_file_methods.htm
廣告