print console sys.stdout

sys.stdout = open("test.txt", "w")

print("Hello World")

sys.stdout.close()
# TEST.TXT:
# Hello World

Here is what the above code is Doing:
1. We’re using the sys module to open a file called test.txt.
2. We’re using the sys module to redirect the output of print to the file we just opened.
3. We’re printing “Hello World” to the file.
4. We’re closing the file.

Now, if we open test.txt, we’ll see “Hello World” in it.

We can also use the sys module to redirect the output of print to a file like this: