python print ot file code example
Example 1: fastest way to output text file in python + Cout
import sys
print('This message will be displayed on the screen.')
original_stdout = sys.stdout # Save a reference to the original standard output
with open('filename.txt', 'w') as f:
sys.stdout = f # Change the standard output to the file we created.
print('This message will be written to a file.')
sys.stdout = original_stdout # Reset the standard output to its original value
Example 2: python write to file
# open a file you can use the function open
file = open("myFile.txt", "w")
#here we have "open", and that's the main function
# that opens the file, next we have 2 arguments
# FILENAME and OPENING MODE
# in the filename argument you just have to write the file's location
# or if the script is in that location just write the filename
# in the opening mode you have to write in which mode you want
# to open your file, i'll list some here:
# "w" for writing to a file
# "r" for reading to a file
# "r+" for both reading and writing
# "a" to append to a file
#to write to the file use "file.write"
file.write("This has been written by a program")
#and finally to close the file when you're done with it
file.close()
# hope this helped and remember that in "w" mode it
#deletes the content of the file and replaces
# it with a new one, if you want to add something
# to a file use "a" mode