Python isatty method:

The isatty is a method of IOBase class in Python. This method returns True if the file stream is interactive or connected to a terminal/TTY device. Otherwise, it returns False. In other words, a file is interactive if it is connected to a terminal device. In such a case this method return a true value. Note that if a file-like object is not associated with a real file, this method should not be implemented.

Method Signature

The signature for the isatty() method is as shown below.

fileObject.isatty()

Method parameters and return type

  • Here, the isatty method doesn’t take any parameters.
  • However, it returns a boolean value True or False.

Python isatty method Examples:

Example 1: In this case, we will open a file in write mode and check if it is interactive or not.

# creating a file 
f1 = open("test.txt", "w")

# Writing 
f1.write("Hello World")
f1.write("\nPython Programming")
print("Is file connected to a tty ?",f1.isatty())

# closing
f1.close()

Output

Is file connected to a tty ? False

Example 2: In this case, we will open a file in reading mode and check if it is interactive or not.

# creating a file 
f1 = open("test.txt", "r")

# Reading 
print(f1.read())
print("Is file connected to a tty ?",f1.isatty())

# closing
f1.close()

Output

Hello World
Python Programming
Is file connected to a tty ? False

Example 3: In this case, we will open a file in append mode and check if it is interactive or not.

# creating a file 
f1 = open("test.txt", "a")

# Appending content
f1.write("Its fun to learn Programming")
print("Is file connected to a tty ?",f1.isatty())

# closing
f1.close()

Output

Is file connected to a tty ? False

Conclusion

Hence, the isatty() method checks if the file is interactive or not.

References

Happy Learning 🙂