34
loading...
This website collects cookies to deliver better user experience
print()
method accepts the file parameter as one of the arguments, and using this, we can print the standard output to a file.sys.stdout
, which prints the output on the screen.open()
function (if file is not available it will create a new file) and writes all the text specified inside the print statement. Once the content is written to a file, we close the file using the close()
method.# Print to the text file
file = open('log.txt', 'w')
print('This is a sample print statement', file = file)
print('Hello World', file = file)
file.close()
This is a sample print statement
Hello World
# Appends the print statement into a log.txt
print("Welcome to ItsMyCode", file=open('log.txt','a'))
Welcome to ItsMyCode
print()
function will be written to a file instead of displaying in the console. sys
module and setting the stdout
to a file or file-like object.import sys
# Prints in a console/terminal
print('Default mode: Prints on a console.')
# Store the reference of original standard output into variable
original_stdout = sys.stdout
# Create or open an existing file in write mode
with open('log.txt', 'w') as file:
# Set the stdout to file object
sys.stdout = file
print('File Mode: Print text to a file.')
# Set the stdout back to the original or default mode
sys.stdout = original_stdout
print('Default Mode: Prints again on a console.')
Hello Welcome to Python Tutorials !!!
File Mode: Print text to a file.
Default mode: Prints on a console.
Default Mode: Prints again on a console.
main.py
with the following code.python3 main.py > output.txt
print("Hello World !!!")
output.txt
file, you can see the below content written into the text file.Hello World !!!