Python File isatty() Method



The Python File isatty() method checks whether the file stream is interactive or not. The file stream is said to be interactive if the file is connected to the "tty" type device. That is what the name of this method, "is a tty", suggests.

The "tty" device is an abbreviation for "Teletypewriter" device. It is an input device that is used to perform I/O operations, i.e. it is an interface that controls the communication between the terminal and the Python program.

Syntax

Following is the syntax for the Python File isatty() method −

fileObject.isatty();

Parameters

The method does not accept any parameters.

Return Value

This method returns true if the file is connected (is associated with a terminal device) to a tty(-like) device, else false.

Example

The following example shows the usage of the Python File isatty() method. In here, we are making use of a file object to open a file in the "writing binary" mode (wb). Then, we are calling the method on this file object created to check whether the file is connected to a tty device or not.

# 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()

When we run above program, it produces following result −

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

Example

However, if the file does not exist in the directory, the method will raise a FileNotFound Error.

# 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()

Let us compile and run the program above, the output is displayed as follows −

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
Advertisements